home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 2.iso / nt / emacssrc.zip / EMACSSRC.TAR / emacs-19.17 / src / keyboard.c < prev    next >
C/C++ Source or Header  |  1993-10-15  |  162KB  |  5,400 lines

  1. /* Keyboard and mouse input; editor command loop.
  2.    Copyright (C) 1985, 1986, 1987, 1988, 1989, 1993 Free Software Foundation, Inc.
  3.  
  4. This file is part of GNU Emacs.
  5.  
  6. GNU Emacs is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2, or (at your option)
  9. any later version.
  10.  
  11. GNU Emacs is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with GNU Emacs; see the file COPYING.  If not, write to
  18. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20. /* Allow config.h to undefine symbols found here.  */
  21.  
  22. #include <signal.h>
  23.  
  24. #include "config.h"
  25. #include <stdio.h>
  26. #undef NULL
  27. #include "termchar.h"
  28. #include "termopts.h"
  29. #include "lisp.h"
  30. #include "macros.h"
  31. #include "frame.h"
  32. #include "window.h"
  33. #include "commands.h"
  34. #include "buffer.h"
  35. #include "disptab.h"
  36. #include "dispextern.h"
  37. #include "keyboard.h"
  38. #include "intervals.h"
  39. #include "blockinput.h"
  40. #include "termhooks.h"
  41. #include <setjmp.h>
  42. #include <errno.h>
  43.  
  44. #ifdef WINDOWSNT
  45. #define    NOMINMAX
  46. #include <windows.h>
  47. #include "ntsig.h"
  48. /* Disable warning about \C */
  49. #pragma warning(disable:4129)
  50. #endif /* WINDOWSNT */
  51.  
  52. #ifndef VMS
  53. #ifndef WINDOWSNT
  54. #include <sys/ioctl.h>
  55. #endif /* !WINDOWSNT */
  56. #endif
  57.  
  58. #include "syssignal.h"
  59. #include "systty.h"
  60. #include "systime.h"
  61.  
  62. #ifdef STDC_HEADERS
  63. #include <stdlib.h>
  64. #endif
  65. #include "keyboard_p.h"
  66. #include "keyboard_d.h"
  67. #include "xdisp_p.h"
  68. #include "cmds_p.h"
  69. #include "sysdep_p.h"
  70. #include "window_d.h"
  71. #include "dispnew_d.h"
  72. #include "alloca_p.h"
  73. static int echo_length _P_((void));
  74. static void echo_truncate _P_((int len));
  75. static void add_command_key _P_((Lisp_Object key));
  76. static int readable_events _P_((void));
  77. static Lisp_Object tracking_off _P_((Lisp_Object old_value));
  78. static Lisp_Object kbd_buffer_get_event _P_((void));
  79. static Lisp_Object make_lispy_event _P_((struct input_event *event));
  80. static Lisp_Object make_lispy_movement _P_((FRAME_PTR frame,
  81.                                             Lisp_Object bar_window,
  82.                                             enum scroll_bar_part part,
  83.                                             Lisp_Object x, Lisp_Object y,
  84.                                             unsigned long time));
  85. static Lisp_Object make_lispy_switch_frame _P_((Lisp_Object frame));
  86. static int parse_modifiers_uncached _P_((Lisp_Object symbol,
  87.                                          int *modifier_end));
  88. static Lisp_Object apply_modifiers_uncached _P_((int modifiers, char *base,
  89.                                                  int base_len));
  90. static Lisp_Object lispy_modifier_list _P_((int modifiers));
  91. static Lisp_Object parse_modifiers _P_((Lisp_Object symbol));
  92. static Lisp_Object apply_modifiers _P_((int modifiers, Lisp_Object base));
  93. static Lisp_Object modify_event_symbol _P_((int symbol_num,
  94.                                             unsigned int modifiers,
  95.                                             Lisp_Object symbol_kind,
  96.                                             char **name_table,
  97.                                             Lisp_Object *symbol_table,
  98.                                             int table_size));
  99. static void get_input_pending _P_((int *addr));
  100. static int read_avail_input _P_((int expected));
  101. static Lisp_Object menu_bar_one_keymap _P_((Lisp_Object keymap,
  102.                                             Lisp_Object result));
  103. static Lisp_Object menu_bar_item _P_((Lisp_Object key, Lisp_Object item_string,
  104.                                       Lisp_Object def, Lisp_Object result));
  105. static Lisp_Object read_char_menu_prompt _P_((int nmaps, Lisp_Object *maps,
  106.                                               Lisp_Object prev_event,
  107.                                               int *used_mouse_menu));
  108. static int follow_key _P_((Lisp_Object key, int nmaps, Lisp_Object *current,
  109.                            Lisp_Object *defs, Lisp_Object *next));
  110. static int read_key_sequence _P_((Lisp_Object *keybuf, int bufsize,
  111.                                   char *prompt));
  112.  
  113. extern int errno;
  114.  
  115. /* Variables for blockinput.h: */
  116.  
  117. /* Non-zero if interrupt input is blocked right now.  */
  118. int interrupt_input_blocked;
  119.  
  120. /* Nonzero means an input interrupt has arrived
  121.    during the current critical section.  */
  122. int interrupt_input_pending;
  123.  
  124.  
  125. #ifdef HAVE_X_WINDOWS
  126. extern Lisp_Object Vmouse_grabbed;
  127.  
  128. /* Make all keyboard buffers much bigger when using X windows.  */
  129. #define KBD_BUFFER_SIZE 4096
  130. #else    /* No X-windows, character input */
  131. #define KBD_BUFFER_SIZE 256
  132. #endif    /* No X-windows */
  133.  
  134. /* Following definition copied from eval.c */
  135.  
  136. struct backtrace
  137.   {
  138.     struct backtrace *next;
  139.     Lisp_Object *function;
  140.     Lisp_Object *args;    /* Points to vector of args. */
  141.     int nargs;        /* length of vector.  If nargs is UNEVALLED,
  142.                args points to slot holding list of
  143.                unevalled args */
  144.     char evalargs;
  145.   };
  146.  
  147. /* Non-nil disable property on a command means
  148.    do not execute it; call disabled-command-hook's value instead.  */
  149. Lisp_Object Qdisabled, Qdisabled_command_hook;
  150.  
  151. #define NUM_RECENT_KEYS (100)
  152. int recent_keys_index;    /* Index for storing next element into recent_keys */
  153. int total_keys;        /* Total number of elements stored into recent_keys */
  154. Lisp_Object recent_keys; /* A vector, holding the last 100 keystrokes */
  155.  
  156. /* Vector holding the key sequence that invoked the current command.
  157.    It is reused for each command, and it may be longer than the current
  158.    sequence; this_command_key_count indicates how many elements
  159.    actually mean something.
  160.    It's easier to staticpro a single Lisp_Object than an array.  */
  161. Lisp_Object this_command_keys;
  162. int this_command_key_count;
  163.  
  164. extern int minbuf_level;
  165.  
  166. extern struct backtrace *backtrace_list;
  167.  
  168. /* Nonzero means do menu prompting.  */
  169. static int menu_prompting;
  170.  
  171. /* Character to see next line of menu prompt.  */
  172. static Lisp_Object menu_prompt_more_char;
  173.  
  174. /* For longjmp to where kbd input is being done.  */
  175. static jmp_buf getcjmp;
  176.  
  177. /* True while doing kbd input.  */
  178. int waiting_for_input;
  179.  
  180. /* True while displaying for echoing.   Delays C-g throwing.  */
  181. static int echoing;
  182.  
  183. /* Nonzero means C-G should cause immediate error-signal.  */
  184. int immediate_quit;
  185.  
  186. /* Character to recognize as the help char.  */
  187. Lisp_Object Vhelp_char;
  188.  
  189. /* Form to execute when help char is typed.  */
  190. Lisp_Object Vhelp_form;
  191.  
  192. /* Command to run when the help character follows a prefix key.  */
  193. Lisp_Object Vprefix_help_command;
  194.  
  195. /* List of items that should move to the end of the menu bar.  */
  196. Lisp_Object Vmenu_bar_final_items;
  197.  
  198. /* Character that causes a quit.  Normally C-g.
  199.  
  200.    If we are running on an ordinary terminal, this must be an ordinary
  201.    ASCII char, since we want to make it our interrupt character.
  202.  
  203.    If we are not running on an ordinary terminal, it still needs to be
  204.    an ordinary ASCII char.  This character needs to be recognized in
  205.    the input interrupt handler.  At this point, the keystroke is
  206.    represented as a struct input_event, while the desired quit
  207.    character is specified as a lispy event.  The mapping from struct
  208.    input_events to lispy events cannot run in an interrupt handler,
  209.    and the reverse mapping is difficult for anything but ASCII
  210.    keystrokes.
  211.  
  212.    FOR THESE ELABORATE AND UNSATISFYING REASONS, quit_char must be an
  213.    ASCII character.  */
  214. int quit_char;
  215.  
  216. extern Lisp_Object current_global_map;
  217. extern int minibuf_level;
  218.  
  219. /* Current depth in recursive edits.  */
  220. int command_loop_level;
  221.  
  222. /* Total number of times command_loop has read a key sequence.  */
  223. int num_input_keys;
  224.  
  225. /* Last input character read as a command.  */
  226. Lisp_Object last_command_char;
  227.  
  228. /* Last input character read as a command, not counting menus
  229.    reached by the mouse.  */
  230. Lisp_Object last_nonmenu_event;
  231.  
  232. /* Last input character read for any purpose.  */
  233. Lisp_Object last_input_char;
  234.  
  235. /* If not Qnil, a list of objects to be read as subsequent command input.  */
  236. Lisp_Object unread_command_events;
  237.  
  238. /* If not -1, an event to be read as subsequent command input.  */
  239. int unread_command_char;
  240.  
  241. /* If not Qnil, this is a switch-frame event which we decided to put
  242.    off until the end of a key sequence.  This should be read as the
  243.    next command input, after any unread_command_events.
  244.  
  245.    read_key_sequence uses this to delay switch-frame events until the
  246.    end of the key sequence; Fread_char uses it to put off switch-frame
  247.    events until a non-ASCII event is acceptable as input.  */
  248. Lisp_Object unread_switch_frame;
  249.  
  250. /* A mask of extra modifier bits to put into every keyboard char.  */
  251. int extra_keyboard_modifiers;
  252.  
  253. /* Char to use as prefix when a meta character is typed in.
  254.    This is bound on entry to minibuffer in case ESC is changed there.  */
  255.  
  256. Lisp_Object meta_prefix_char;
  257.  
  258. /* Last size recorded for a current buffer which is not a minibuffer.  */
  259. static int last_non_minibuf_size;
  260.  
  261. /* Number of idle seconds before an auto-save and garbage collection.  */
  262. static Lisp_Object Vauto_save_timeout;
  263.  
  264. /* Total number of times read_char has returned.  */
  265. int num_input_chars;
  266.  
  267. /* Total number of times read_char has returned, outside of macros.  */
  268. int num_nonmacro_input_chars;
  269.  
  270. /* Auto-save automatically when this many characters have been typed
  271.    since the last time.  */
  272.  
  273. static int auto_save_interval;
  274.  
  275. /* Value of num_nonmacro_input_chars as of last auto save.  */
  276.  
  277. int last_auto_save;
  278.  
  279. /* Last command executed by the editor command loop, not counting
  280.    commands that set the prefix argument.  */
  281.  
  282. Lisp_Object last_command;
  283.  
  284. /* The command being executed by the command loop.
  285.    Commands may set this, and the value set will be copied into last_command
  286.    instead of the actual command.  */
  287. Lisp_Object this_command;
  288.  
  289. #ifdef MULTI_FRAME
  290. /* The frame in which the last input event occurred, or Qmacro if the
  291.    last event came from a macro.  We use this to determine when to
  292.    generate switch-frame events.  This may be cleared by functions
  293.    like Fselect_frame, to make sure that a switch-frame event is
  294.    generated by the next character.  */
  295. Lisp_Object internal_last_event_frame;
  296.  
  297. /* A user-visible version of the above, intended to allow users to
  298.    figure out where the last event came from, if the event doesn't
  299.    carry that information itself (i.e. if it was a character).  */
  300. Lisp_Object Vlast_event_frame;
  301. #endif
  302.  
  303. /* The timestamp of the last input event we received from the X server.
  304.    X Windows wants this for selection ownership.  */
  305. unsigned long last_event_timestamp;
  306.  
  307. Lisp_Object Qself_insert_command;
  308. Lisp_Object Qforward_char;
  309. Lisp_Object Qbackward_char;
  310. Lisp_Object Qundefined;
  311.  
  312. /* read_key_sequence stores here the command definition of the
  313.    key sequence that it reads.  */
  314. Lisp_Object read_key_sequence_cmd;
  315.  
  316. /* Form to evaluate (if non-nil) when Emacs is started.  */
  317. Lisp_Object Vtop_level;
  318.  
  319. /* User-supplied string to translate input characters through.  */
  320. Lisp_Object Vkeyboard_translate_table;
  321.  
  322. /* Keymap mapping ASCII function key sequences onto their preferred forms.  */
  323. extern Lisp_Object Vfunction_key_map;
  324.  
  325. /* Non-nil means deactivate the mark at end of this command.  */
  326. Lisp_Object Vdeactivate_mark;
  327.  
  328. /* Menu bar specified in Lucid Emacs fashion.  */
  329.  
  330. Lisp_Object Vlucid_menu_bar_dirty_flag;
  331. Lisp_Object Qrecompute_lucid_menubar, Qactivate_menubar_hook;
  332.  
  333. /* Hooks to run before and after each command.  */
  334. Lisp_Object Qpre_command_hook, Qpost_command_hook;
  335. Lisp_Object Vpre_command_hook, Vpost_command_hook;
  336.  
  337. /* File in which we write all commands we read.  */
  338. FILE *dribble;
  339.  
  340. /* Nonzero if input is available.  */
  341. int input_pending;
  342.  
  343. /* 1 if should obey 0200 bit in input chars as "Meta", 2 if should
  344.    keep 0200 bit in input chars.  0 to ignore the 0200 bit.  */
  345.  
  346. int meta_key;
  347.  
  348. extern char *pending_malloc_warning;
  349.  
  350. /* Circular buffer for pre-read keyboard input.  */
  351. static struct input_event kbd_buffer[KBD_BUFFER_SIZE];
  352.  
  353. /* Vector to GCPRO the frames and windows mentioned in kbd_buffer.
  354.  
  355.    The interrupt-level event handlers will never enqueue an event on a
  356.    frame which is not in Vframe_list, and once an event is dequeued,
  357.    internal_last_event_frame or the event itself points to the frame.
  358.    So that's all fine.
  359.  
  360.    But while the event is sitting in the queue, it's completely
  361.    unprotected.  Suppose the user types one command which will run for
  362.    a while and then delete a frame, and then types another event at
  363.    the frame that will be deleted, before the command gets around to
  364.    it.  Suppose there are no references to this frame elsewhere in
  365.    Emacs, and a GC occurs before the second event is dequeued.  Now we
  366.    have an event referring to a freed frame, which will crash Emacs
  367.    when it is dequeued.
  368.  
  369.    Similar things happen when an event on a scroll bar is enqueued; the
  370.    window may be deleted while the event is in the queue.
  371.  
  372.    So, we use this vector to protect the frame_or_window field in the
  373.    event queue.  That way, they'll be dequeued as dead frames or
  374.    windows, but still valid lisp objects.
  375.  
  376.    If kbd_buffer[i].kind != no_event, then
  377.      (XVECTOR (kbd_buffer_frame_or_window)->contents[i]
  378.       == kbd_buffer[i].frame_or_window.  */
  379. static Lisp_Object kbd_buffer_frame_or_window;
  380.  
  381. /* Pointer to next available character in kbd_buffer.
  382.    If kbd_fetch_ptr == kbd_store_ptr, the buffer is empty.
  383.    This may be kbd_buffer + KBD_BUFFER_SIZE, meaning that the the
  384.    next available char is in kbd_buffer[0].  */
  385. static struct input_event *kbd_fetch_ptr;
  386.  
  387. /* Pointer to next place to store character in kbd_buffer.  This
  388.    may be kbd_buffer + KBD_BUFFER_SIZE, meaning that the next
  389.    character should go in kbd_buffer[0].  */
  390. #ifdef __STDC__
  391. volatile
  392. #endif
  393. static struct input_event *kbd_store_ptr;
  394.  
  395. /* The above pair of variables forms a "queue empty" flag.  When we
  396.    enqueue a non-hook event, we increment kbd_write_count.  When we
  397.    dequeue a non-hook event, we increment kbd_read_count.  We say that
  398.    there is input available iff the two counters are not equal.
  399.  
  400.    Why not just have a flag set and cleared by the enqueuing and
  401.    dequeuing functions?  Such a flag could be screwed up by interrupts
  402.    at inopportune times.  */
  403.  
  404. /* If this flag is non-zero, we check mouse_moved to see when the
  405.    mouse moves, and motion events will appear in the input stream.  If
  406.    it is zero, mouse motion is ignored.  */
  407. static int do_mouse_tracking;
  408.  
  409. /* The window system handling code should set this if the mouse has
  410.    moved since the last call to the mouse_position_hook.  Calling that
  411.    hook should clear this.  Code assumes that if this is set, it can
  412.    call mouse_position_hook to get the promised position, so don't set
  413.    it unless you're prepared to substantiate the claim!  */
  414. int mouse_moved;
  415.  
  416. /* True iff there is an event in kbd_buffer, or if mouse tracking is
  417.    enabled and there is a new mouse position in the mouse movement
  418.    buffer.  Note that if this is false, that doesn't mean that there
  419.    is readable input; all the events in the queue might be button-up
  420.    events, and do_mouse_tracking might be off.  */
  421. #define EVENT_QUEUES_EMPTY \
  422.   ((kbd_fetch_ptr == kbd_store_ptr) && (!do_mouse_tracking || !mouse_moved))
  423.  
  424.  
  425. /* Symbols to head events.  */
  426. Lisp_Object Qmouse_movement;
  427. Lisp_Object Qscroll_bar_movement;
  428. Lisp_Object Qswitch_frame;
  429.  
  430. /* Symbols to denote kinds of events.  */
  431. Lisp_Object Qfunction_key;
  432. Lisp_Object Qmouse_click;
  433. /* Lisp_Object Qmouse_movement; - also an event header */
  434.  
  435. /* Properties of event headers.  */
  436. Lisp_Object Qevent_kind;
  437. Lisp_Object Qevent_symbol_elements;
  438.  
  439. Lisp_Object Qmenu_enable;
  440.  
  441. /* An event header symbol HEAD may have a property named
  442.    Qevent_symbol_element_mask, which is of the form (BASE MODIFIERS);
  443.    BASE is the base, unmodified version of HEAD, and MODIFIERS is the
  444.    mask of modifiers applied to it.  If present, this is used to help
  445.    speed up parse_modifiers.  */
  446. Lisp_Object Qevent_symbol_element_mask;
  447.  
  448. /* An unmodified event header BASE may have a property named
  449.    Qmodifier_cache, which is an alist mapping modifier masks onto
  450.    modified versions of BASE.  If present, this helps speed up
  451.    apply_modifiers.  */
  452. Lisp_Object Qmodifier_cache;
  453.  
  454. /* Symbols to use for parts of windows.  */
  455. Lisp_Object Qmode_line;
  456. Lisp_Object Qvertical_line;
  457. Lisp_Object Qvertical_scroll_bar;
  458. Lisp_Object Qmenu_bar;
  459.  
  460. extern Lisp_Object Qmenu_enable;
  461.  
  462. /* Address (if not 0) of EMACS_TIME to zero out if a SIGIO interrupt
  463.    happens.  */
  464. EMACS_TIME *input_available_clear_time;
  465.  
  466. /* Nonzero means use SIGIO interrupts; zero means use CBREAK mode.
  467.    Default is 1 if INTERRUPT_INPUT is defined.  */
  468. int interrupt_input;
  469.  
  470. /* Nonzero while interrupts are temporarily deferred during redisplay.  */
  471. int interrupts_deferred;
  472.  
  473. /* nonzero means use ^S/^Q for flow control.  */
  474. int flow_control;
  475.  
  476. /* Allow m- file to inhibit use of FIONREAD.  */
  477. #ifdef BROKEN_FIONREAD
  478. #undef FIONREAD
  479. #endif
  480.  
  481. /* We are unable to use interrupts if FIONREAD is not available,
  482.    so flush SIGIO so we won't try.  */
  483. #ifndef FIONREAD
  484. #ifdef SIGIO
  485. #undef SIGIO
  486. #endif
  487. #endif
  488.  
  489. /* If we support X Windows, and won't get an interrupt when input
  490.    arrives from the server, poll periodically so we can detect C-g.  */
  491. #ifdef HAVE_X_WINDOWS
  492. #ifndef SIGIO
  493. #define POLL_FOR_INPUT
  494. #endif
  495. #endif
  496.  
  497. /* Global variable declarations.  */
  498.  
  499. /* Function for init_keyboard to call with no args (if nonzero).  */
  500. void (*keyboard_init_hook) _P_((void));
  501.  
  502. /* > 0 if we are to echo keystrokes.  */
  503. static int echo_keystrokes;
  504.  
  505. /* Nonzero means echo each character as typed.  */
  506. static int immediate_echo;
  507.  
  508. /* The text we're echoing in the modeline - partial key sequences,
  509.    usually.  '\0'-terminated.  This really shouldn't have a fixed size.  */
  510. static char echobuf[300];
  511.  
  512. /* Where to append more text to echobuf if we want to.  */
  513. static char *echoptr;
  514.  
  515. #ifndef min
  516. #define    min(a,b)    ((a)<(b)?(a):(b))
  517. #endif
  518. #ifndef max
  519. #define    max(a,b)    ((a)>(b)?(a):(b))
  520. #endif
  521.  
  522. /* Install the string STR as the beginning of the string of echoing,
  523.    so that it serves as a prompt for the next character.
  524.    Also start echoing.  */
  525.  
  526. _VOID_
  527. echo_prompt (str)
  528.      char *str;
  529. {
  530.   int len = strlen (str);
  531.   if (len > sizeof echobuf - 4)
  532.     len = sizeof echobuf - 4;
  533.   bcopy (str, echobuf, len);
  534.   echoptr = echobuf + len;
  535.   *echoptr = '\0';
  536.  
  537.   echo ();
  538. }
  539.  
  540. /* Add C to the echo string, if echoing is going on.  
  541.    C can be a character, which is printed prettily ("M-C-x" and all that
  542.    jazz), or a symbol, whose name is printed.  */
  543.  
  544. _VOID_
  545. echo_char (c)
  546.      Lisp_Object c;
  547. {
  548.   if (immediate_echo)
  549.     {
  550.       char *ptr = echoptr;
  551.       
  552.       if (ptr != echobuf)
  553.     *ptr++ = ' ';
  554.  
  555.       /* If someone has passed us a composite event, use its head symbol.  */
  556.       c = EVENT_HEAD (c);
  557.  
  558.       if (XTYPE (c) == Lisp_Int)
  559.     {
  560.       if (ptr - echobuf > sizeof echobuf - 6)
  561.         return;
  562.  
  563.       ptr = push_key_description (XINT (c), ptr);
  564.     }
  565.       else if (XTYPE (c) == Lisp_Symbol)
  566.     {
  567.       struct Lisp_String *name = XSYMBOL (c)->name;
  568.       if (((ptr - echobuf) + name->size + 4) > sizeof echobuf)
  569.         return;
  570.       bcopy (name->data, ptr, name->size);
  571.       ptr += name->size;
  572.     }
  573.  
  574.       if (echoptr == echobuf && EQ (c, Vhelp_char))
  575.     {
  576.       strcpy (ptr, " (Type ? for further options)");
  577.       ptr += strlen (ptr);
  578.     }
  579.  
  580.       *ptr = 0;
  581.       echoptr = ptr;
  582.  
  583.       echo ();
  584.     }
  585. }
  586.  
  587. /* Temporarily add a dash to the end of the echo string if it's not
  588.    empty, so that it serves as a mini-prompt for the very next character.  */
  589.  
  590. _VOID_
  591. echo_dash ()
  592. {
  593.   if (!immediate_echo && echoptr == echobuf)
  594.     return;
  595.   /* Do nothing if not echoing at all.  */
  596.   if (echoptr == 0)
  597.     return;
  598.  
  599.   /* Put a dash at the end of the buffer temporarily,
  600.      but make it go away when the next character is added.  */
  601.   echoptr[0] = '-';
  602.   echoptr[1] = 0;
  603.  
  604.   echo ();
  605. }
  606.  
  607. /* Display the current echo string, and begin echoing if not already
  608.    doing so.  */
  609.  
  610. _VOID_
  611. echo ()
  612. {
  613.   if (!immediate_echo)
  614.     {
  615.       int i;
  616.       immediate_echo = 1;
  617.  
  618.       for (i = 0; i < this_command_key_count; i++)
  619.     echo_char (XVECTOR (this_command_keys)->contents[i]);
  620.       echo_dash ();
  621.     }
  622.  
  623.   echoing = 1;
  624.   message1 (echobuf);
  625.   echoing = 0;
  626.  
  627.   if (waiting_for_input && !NILP (Vquit_flag))
  628.     quit_throw_to_read_char ();
  629. }
  630.  
  631. /* Turn off echoing, for the start of a new command.  */
  632.  
  633. _VOID_
  634. cancel_echoing ()
  635. {
  636.   immediate_echo = 0;
  637.   echoptr = echobuf;
  638. }
  639.  
  640. /* Return the length of the current echo string.  */
  641.  
  642. static int
  643. echo_length ()
  644. {
  645.   return echoptr - echobuf;
  646. }
  647.  
  648. /* Truncate the current echo message to its first LEN chars.
  649.    This and echo_char get used by read_key_sequence when the user
  650.    switches frames while entering a key sequence.  */
  651.  
  652. static void
  653. echo_truncate (len)
  654.      int len;
  655. {
  656.   echobuf[len] = '\0';
  657.   echoptr = echobuf + len;
  658. }
  659.  
  660.  
  661. /* Functions for manipulating this_command_keys.  */
  662. static void
  663. add_command_key (key)
  664.      Lisp_Object key;
  665. {
  666.   int size = XVECTOR (this_command_keys)->size;
  667.  
  668.   if (this_command_key_count >= size)
  669.     {
  670.       Lisp_Object new_keys = Fmake_vector (make_number (size * 2), Qnil);
  671.  
  672.       bcopy (XVECTOR (this_command_keys)->contents,
  673.          XVECTOR (new_keys)->contents,
  674.          size * sizeof (Lisp_Object));
  675.  
  676.       this_command_keys = new_keys;
  677.     }
  678.  
  679.   XVECTOR (this_command_keys)->contents[this_command_key_count++] = key;
  680. }
  681.  
  682. Lisp_Object
  683. recursive_edit_1 ()
  684. {
  685.   int count = specpdl_ptr - specpdl;
  686.   Lisp_Object val;
  687.  
  688.   if (command_loop_level > 0)
  689.     {
  690.       specbind (Qstandard_output, Qt);
  691.       specbind (Qstandard_input, Qt);
  692.     }
  693.  
  694.   val = command_loop ();
  695.   if (EQ (val, Qt))
  696.     Fsignal (Qquit, Qnil);
  697.  
  698.   return unbind_to (count, Qnil);
  699. }
  700.  
  701. /* When an auto-save happens, record the "time", and don't do again soon.  */
  702. _VOID_
  703. record_auto_save ()
  704. {
  705.   last_auto_save = num_nonmacro_input_chars;
  706. }
  707.  
  708. DEFUN ("recursive-edit", Frecursive_edit, Srecursive_edit, 0, 0, "",
  709.   "Invoke the editor command loop recursively.\n\
  710. To get out of the recursive edit, a command can do `(throw 'exit nil)';\n\
  711. that tells this function to return.\n\
  712. Alternately, `(throw 'exit t)' makes this function signal an error.\n\
  713. This function is called by the editor initialization to begin editing.")
  714.   ()
  715. {
  716.   int count = specpdl_ptr - specpdl;
  717.  
  718.   command_loop_level++;
  719.   update_mode_lines = 1;
  720.  
  721.   record_unwind_protect (recursive_edit_unwind,
  722.              (command_loop_level
  723.               && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
  724.              ? Fcurrent_buffer ()
  725.              : Qnil);
  726.   recursive_edit_1 ();
  727.   return unbind_to (count, Qnil);
  728. }
  729.  
  730. Lisp_Object
  731. recursive_edit_unwind (buffer)
  732.      Lisp_Object buffer;
  733. {
  734.   if (!NILP (buffer))
  735.     Fset_buffer (buffer);
  736.  
  737.   command_loop_level--;
  738.   update_mode_lines = 1;
  739.   return Qnil;
  740. }
  741.  
  742. Lisp_Object
  743. cmd_error (data)
  744.      Lisp_Object data;
  745. {
  746.   Lisp_Object errmsg, tail, errname, file_error;
  747.   Lisp_Object stream;
  748.   struct gcpro gcpro1;
  749.   int i;
  750.  
  751.   Vquit_flag = Qnil;
  752.   Vinhibit_quit = Qt;
  753.   Vstandard_output = Qt;
  754.   Vstandard_input = Qt;
  755.   Vexecuting_macro = Qnil;
  756.   echo_area_glyphs = 0;
  757.  
  758.   /* If the window system or terminal frame hasn't been initialized
  759.      yet, or we're not interactive, it's best to dump this message out
  760.      to stderr and exit.  */
  761.   if (! FRAME_MESSAGE_BUF (selected_frame)
  762.       || noninteractive)
  763.     stream = Qexternal_debugging_output;
  764.   else
  765.     {
  766.       Fdiscard_input ();
  767.       bitch_at_user ();
  768.       stream = Qt;
  769.     }
  770.  
  771.   errname = Fcar (data);
  772.  
  773.   if (EQ (errname, Qerror))
  774.     {
  775.       data = Fcdr (data);
  776.       if (!CONSP (data)) data = Qnil;
  777.       errmsg = Fcar (data);
  778.       file_error = Qnil;
  779.     }
  780.   else
  781.     {
  782.       errmsg = Fget (errname, Qerror_message);
  783.       file_error = Fmemq (Qfile_error,
  784.               Fget (errname, Qerror_conditions));
  785.     }
  786.  
  787.   /* Print an error message including the data items.
  788.      This is done by printing it into a scratch buffer
  789.      and then making a copy of the text in the buffer. */
  790.  
  791.   if (!CONSP (data)) data = Qnil;
  792.   tail = Fcdr (data);
  793.   GCPRO1 (tail);
  794.  
  795.   /* For file-error, make error message by concatenating
  796.      all the data items.  They are all strings.  */
  797.   if (!NILP (file_error) && !NILP (tail))
  798.     errmsg = XCONS (tail)->car, tail = XCONS (tail)->cdr;
  799.  
  800.   if (XTYPE (errmsg) == Lisp_String)
  801.     Fprinc (errmsg, stream);
  802.   else
  803.     write_string_1 ("peculiar error", -1, stream);
  804.  
  805.   for (i = 0; CONSP (tail); tail = Fcdr (tail), i++)
  806.     {
  807.       write_string_1 (i ? ", " : ": ", 2, stream);
  808.       if (!NILP (file_error))
  809.     Fprinc (Fcar (tail), stream);
  810.       else
  811.     Fprin1 (Fcar (tail), stream);
  812.     }
  813.   UNGCPRO;
  814.  
  815.   /* If the window system or terminal frame hasn't been initialized
  816.      yet, or we're in -batch mode, this error should cause Emacs to exit.  */
  817.   if (! FRAME_MESSAGE_BUF (selected_frame)
  818.       || noninteractive)
  819.     {
  820.       Fterpri (stream);
  821.       Fkill_emacs (make_number (-1));
  822.     }
  823.  
  824.   Vquit_flag = Qnil;
  825.  
  826.   Vinhibit_quit = Qnil;
  827.   return make_number (0);
  828. }
  829.  
  830. /* Entry to editor-command-loop.
  831.    This level has the catches for exiting/returning to editor command loop.
  832.    It returns nil to exit recursive edit, t to abort it.  */
  833.  
  834. Lisp_Object
  835. command_loop ()
  836. {
  837.   if (command_loop_level > 0 || minibuf_level > 0)
  838.     {
  839.       return internal_catch (Qexit, command_loop_2, Qnil);
  840.     }
  841.   else
  842.     while (1)
  843.       {
  844.     internal_catch (Qtop_level, top_level_1, Qnil);
  845.     internal_catch (Qtop_level, command_loop_2, Qnil);
  846.     
  847.     /* End of file in -batch run causes exit here.  */
  848.     if (noninteractive)
  849.       Fkill_emacs (Qt);
  850.       }
  851. }
  852.  
  853. /* Here we catch errors in execution of commands within the
  854.    editing loop, and reenter the editing loop.
  855.    When there is an error, cmd_error runs and returns a non-nil
  856.    value to us.  A value of nil means that cmd_loop_1 itself
  857.    returned due to end of file (or end of kbd macro).  */
  858.  
  859. Lisp_Object
  860. command_loop_2 (dummy)
  861.     /* Needs a parameter */
  862.     Lisp_Object dummy;
  863. {
  864.   register Lisp_Object val;
  865.  
  866.   do
  867.     val = internal_condition_case (command_loop_1, Qerror, cmd_error);
  868.   while (!NILP (val));
  869.  
  870.   return Qnil;
  871. }
  872.  
  873. Lisp_Object
  874. top_level_2 _P_((void))
  875. {
  876.   return Feval (Vtop_level);
  877. }
  878.  
  879. Lisp_Object
  880. top_level_1 (dummy)
  881.     /* Needs a parameter */
  882.     Lisp_Object dummy;
  883. {
  884.   /* On entry to the outer level, run the startup file */
  885.   if (!NILP (Vtop_level))
  886.     internal_condition_case (top_level_2, Qerror, cmd_error);
  887.   else if (!NILP (Vpurify_flag))
  888.     message ("Bare impure Emacs (standard Lisp code not loaded)");
  889.   else
  890.     message ("Bare Emacs (standard Lisp code not loaded)");
  891.   return Qnil;
  892. }
  893.  
  894. DEFUN ("top-level", Ftop_level, Stop_level, 0, 0, "",
  895.   "Exit all recursive editing levels.")
  896.   ()
  897. {
  898.   Fthrow (Qtop_level, Qnil);
  899.   return Qt;
  900. }
  901.  
  902. DEFUN ("exit-recursive-edit", Fexit_recursive_edit, Sexit_recursive_edit, 0, 0, "",
  903.   "Exit from the innermost recursive edit or minibuffer.")
  904.   ()
  905. {
  906.   if (command_loop_level > 0 || minibuf_level > 0)
  907.     Fthrow (Qexit, Qnil);
  908.  
  909.   error ("No recursive edit is in progress");
  910.   return Qnil;
  911. }
  912.  
  913. DEFUN ("abort-recursive-edit", Fabort_recursive_edit, Sabort_recursive_edit, 0, 0, "",
  914.   "Abort the command that requested this recursive edit or minibuffer input.")
  915.   ()
  916. {
  917.   if (command_loop_level > 0 || minibuf_level > 0)
  918.     Fthrow (Qexit, Qt);
  919.  
  920.   error ("No recursive edit is in progress");
  921.   return Qnil;
  922. }
  923.  
  924. /* This is the actual command reading loop,
  925.    sans error-handling encapsulation.  */
  926.  
  927. Lisp_Object
  928. command_loop_1 ()
  929. {
  930.   Lisp_Object cmd;
  931. #if 0
  932.   Lisp_Object tem;
  933. #endif
  934.   int lose;
  935.   int nonundocount;
  936.   Lisp_Object keybuf[30];
  937.   int i;
  938.   int no_redisplay;
  939.   int no_direct;
  940.   int prev_modiff;
  941.   struct buffer *prev_buffer;
  942.  
  943.   Vprefix_arg = Qnil;
  944.   Vdeactivate_mark = Qnil;
  945.   waiting_for_input = 0;
  946.   cancel_echoing ();
  947.  
  948.   /* Don't clear out last_command at the beginning of a macro.  */
  949.   if (XTYPE (Vexecuting_macro) != Lisp_String)
  950.     last_command = Qt;
  951.  
  952.   nonundocount = 0;
  953.   no_redisplay = 0;
  954.   this_command_key_count = 0;
  955.  
  956.   while (1)
  957.     {
  958.       /* Install chars successfully executed in kbd macro.  */
  959.  
  960.       if (defining_kbd_macro && NILP (Vprefix_arg))
  961.     finalize_kbd_macro_chars ();
  962.  
  963.       /* Make sure the current window's buffer is selected.  */
  964.       if (XBUFFER (XWINDOW (selected_window)->buffer) != current_buffer)
  965.     set_buffer_internal (XBUFFER (XWINDOW (selected_window)->buffer));
  966.  
  967.       /* Display any malloc warning that just came out.  Use while because
  968.      displaying one warning can cause another.  */
  969.  
  970.       while (pending_malloc_warning)
  971.     display_malloc_warning ();
  972.  
  973.       no_direct = 0;
  974.  
  975.       Vdeactivate_mark = Qnil;
  976.  
  977.       /* If minibuffer on and echo area in use,
  978.      wait 2 sec and redraw minibuffer.  */
  979.  
  980.       if (minibuf_level && echo_area_glyphs)
  981.     {
  982.       /* Bind inhibit-quit to t so that C-g gets read in
  983.          rather than quitting back to the minibuffer.  */
  984.       int count = specpdl_ptr - specpdl;
  985.       specbind (Qinhibit_quit, Qt);
  986.       Fsit_for (make_number (2), Qnil, Qnil);
  987.       unbind_to (count, Qnil);
  988.  
  989.       echo_area_glyphs = 0;
  990.       no_direct = 1;
  991.       if (!NILP (Vquit_flag))
  992.         {
  993.           Vquit_flag = Qnil;
  994.           unread_command_events = Fcons (make_number (quit_char), Qnil);
  995.         }
  996.     }
  997.  
  998. #ifdef C_ALLOCA
  999.       alloca (0);        /* Cause a garbage collection now */
  1000.                 /* Since we can free the most stuff here.  */
  1001. #endif /* C_ALLOCA */
  1002.  
  1003. #if 0
  1004. #ifdef MULTI_FRAME
  1005.       /* Select the frame that the last event came from.  Usually,
  1006.      switch-frame events will take care of this, but if some lisp
  1007.      code swallows a switch-frame event, we'll fix things up here.
  1008.      Is this a good idea?  */
  1009.       if (XTYPE (internal_last_event_frame) == Lisp_Frame
  1010.       && XFRAME (internal_last_event_frame) != selected_frame)
  1011.     Fselect_frame (internal_last_event_frame, Qnil);
  1012. #endif
  1013. #endif
  1014.       /* If it has changed current-menubar from previous value,
  1015.      really recompute the menubar from the value.  */
  1016.       if (! NILP (Vlucid_menu_bar_dirty_flag))
  1017.     call0 (Qrecompute_lucid_menubar);
  1018.  
  1019. #if 0 /* This is done in xdisp.c now.  */
  1020. #ifdef MULTI_FRAME
  1021.       for (tem = Vframe_list; CONSP (tem); tem = XCONS (tem)->cdr)
  1022.     {
  1023.       struct frame *f = XFRAME (XCONS (tem)->car);
  1024.       struct window *w = XWINDOW (FRAME_SELECTED_WINDOW (f));
  1025.  
  1026.       /* If the user has switched buffers or windows, we need to
  1027.          recompute to reflect the new bindings.  But we'll
  1028.          recompute when update_mode_lines is set too; that means
  1029.          that people can use force-mode-line-update to request
  1030.          that the menu bar be recomputed.  The adverse effect on
  1031.          the rest of the redisplay algorithm is about the same as
  1032.          windows_or_buffers_changed anyway.  */
  1033.       if (windows_or_buffers_changed
  1034.           || update_mode_lines
  1035.           || (XFASTINT (w->last_modified) < MODIFF
  1036.           && (XFASTINT (w->last_modified)
  1037.               <= XBUFFER (w->buffer)->save_modified)))
  1038.         {
  1039.           struct buffer *prev = current_buffer;
  1040.           current_buffer = XBUFFER (w->buffer);
  1041.           FRAME_MENU_BAR_ITEMS (f) = menu_bar_items ();
  1042.           current_buffer = prev;
  1043.         }
  1044.     }
  1045. #endif /* MULTI_FRAME */
  1046. #endif /* 0 */
  1047.  
  1048.       /* Read next key sequence; i gets its length.  */
  1049.       i = read_key_sequence (keybuf, (sizeof keybuf / sizeof (keybuf[0])), 0);
  1050.  
  1051.       ++num_input_keys;
  1052.  
  1053.       /* Now we have read a key sequence of length I,
  1054.      or else I is 0 and we found end of file.  */
  1055.  
  1056.       if (i == 0)        /* End of file -- happens only in */
  1057.     return Qnil;        /* a kbd macro, at the end.  */
  1058.       /* -1 means read_key_sequence got a menu that was rejected.
  1059.      Just loop around and read another command.  */
  1060.       if (i == -1)
  1061.     {
  1062.       cancel_echoing ();
  1063.       this_command_key_count = 0;
  1064.       continue;
  1065.     }
  1066.  
  1067.       last_command_char = keybuf[i - 1];
  1068.  
  1069.       /* If the previous command tried to force a specific window-start,
  1070.      forget about that, in case this command moves point far away
  1071.      from that position.  */
  1072.       XWINDOW (selected_window)->force_start = Qnil;
  1073.  
  1074.       cmd = read_key_sequence_cmd;
  1075.       if (!NILP (Vexecuting_macro))
  1076.     {
  1077.       if (!NILP (Vquit_flag))
  1078.         {
  1079.           Vexecuting_macro = Qt;
  1080.           QUIT;        /* Make some noise. */
  1081.                 /* Will return since macro now empty. */
  1082.         }
  1083.     }
  1084.  
  1085.       /* Do redisplay processing after this command except in special
  1086.      cases identified below that set no_redisplay to 1.  */
  1087.       no_redisplay = 0;
  1088.  
  1089.       prev_buffer = current_buffer;
  1090.       prev_modiff = MODIFF;
  1091.  
  1092.       /* Execute the command.  */
  1093.  
  1094.       this_command = cmd;
  1095.       if (!NILP (Vpre_command_hook))
  1096.     call1 (Vrun_hooks, Qpre_command_hook);
  1097.  
  1098.       if (NILP (this_command))
  1099.     {
  1100.       /* nil means key is undefined.  */
  1101.       bitch_at_user ();
  1102.       defining_kbd_macro = 0;
  1103.       update_mode_lines = 1;
  1104.       Vprefix_arg = Qnil;
  1105.  
  1106.     }
  1107.       else
  1108.     {
  1109.       if (NILP (Vprefix_arg) && ! no_direct)
  1110.         {
  1111.           /* Recognize some common commands in common situations and
  1112.          do them directly.  */
  1113.           if (EQ (this_command, Qforward_char) && point < ZV)
  1114.         {
  1115.                   struct Lisp_Vector *dp
  1116.             = window_display_table (XWINDOW (selected_window));
  1117.           lose = FETCH_CHAR (point);
  1118.           SET_PT (point + 1);
  1119.           if ((dp
  1120.                ? (XTYPE (DISP_CHAR_VECTOR (dp, lose)) != Lisp_Vector
  1121.               && XVECTOR (DISP_CHAR_VECTOR (dp, lose))->size == 1)
  1122.                : (lose >= 0x20 && lose < 0x7f))
  1123.               && (XFASTINT (XWINDOW (selected_window)->last_modified)
  1124.               >= MODIFF)
  1125.               && (XFASTINT (XWINDOW (selected_window)->last_point)
  1126.               == point - 1)
  1127.               && !windows_or_buffers_changed
  1128.               && EQ (current_buffer->selective_display, Qnil)
  1129.               && !detect_input_pending ()
  1130.               && NILP (Vexecuting_macro))
  1131.             no_redisplay = direct_output_forward_char (1);
  1132.           goto directly_done;
  1133.         }
  1134.           else if (EQ (this_command, Qbackward_char) && point > BEGV)
  1135.         {
  1136.                   struct Lisp_Vector *dp
  1137.             = window_display_table (XWINDOW (selected_window));
  1138.           SET_PT (point - 1);
  1139.           lose = FETCH_CHAR (point);
  1140.           if ((dp
  1141.                ? (XTYPE (DISP_CHAR_VECTOR (dp, lose)) != Lisp_Vector
  1142.               && XVECTOR (DISP_CHAR_VECTOR (dp, lose))->size == 1)
  1143.                : (lose >= 0x20 && lose < 0x7f))
  1144.               && (XFASTINT (XWINDOW (selected_window)->last_modified)
  1145.               >= MODIFF)
  1146.               && (XFASTINT (XWINDOW (selected_window)->last_point)
  1147.               == point + 1)
  1148.               && !windows_or_buffers_changed
  1149.               && EQ (current_buffer->selective_display, Qnil)
  1150.               && !detect_input_pending ()
  1151.               && NILP (Vexecuting_macro))
  1152.             no_redisplay = direct_output_forward_char (-1);
  1153.           goto directly_done;
  1154.         }
  1155.           else if (EQ (this_command, Qself_insert_command)
  1156.                /* Try this optimization only on ascii keystrokes.  */
  1157.                && XTYPE (last_command_char) == Lisp_Int)
  1158.         {
  1159.           unsigned char c = XINT (last_command_char);
  1160.  
  1161.           if (NILP (Vexecuting_macro) &&
  1162.               !EQ (minibuf_window, selected_window))
  1163.             {
  1164.               if (!nonundocount || nonundocount >= 20)
  1165.             {
  1166.               Fundo_boundary ();
  1167.               nonundocount = 0;
  1168.             }
  1169.               nonundocount++;
  1170.             }
  1171.           lose = (XFASTINT (XWINDOW (selected_window)->last_modified)
  1172.               < MODIFF)
  1173.             || (XFASTINT (XWINDOW (selected_window)->last_point)
  1174.               != point)
  1175.             || MODIFF <= current_buffer->save_modified
  1176.             || windows_or_buffers_changed
  1177.             || !EQ (current_buffer->selective_display, Qnil)
  1178.             || detect_input_pending ()
  1179.             || !NILP (Vexecuting_macro);
  1180.           if (internal_self_insert (c, 0))
  1181.             {
  1182.               lose = 1;
  1183.               nonundocount = 0;
  1184.             }
  1185.           if (!lose &&
  1186.               (point == ZV || FETCH_CHAR (point) == '\n'))
  1187.             {
  1188.               struct Lisp_Vector *dp
  1189.             = window_display_table (XWINDOW (selected_window));
  1190.               int lose = c;
  1191.  
  1192.               if (dp)
  1193.             {
  1194.               Lisp_Object obj = DISP_CHAR_VECTOR (dp, lose);
  1195.  
  1196.               if (XTYPE (obj) == Lisp_Vector
  1197.                   && XVECTOR (obj)->size == 1
  1198.                   && (XTYPE (obj = XVECTOR (obj)->contents[0])
  1199.                   == Lisp_Int))
  1200.                 no_redisplay =
  1201.                   direct_output_for_insert (XINT (obj));
  1202.             }
  1203.               else
  1204.             {
  1205.               if (lose >= 0x20 && lose <= 0x7e)
  1206.                 no_redisplay = direct_output_for_insert (lose);
  1207.             }
  1208.             }
  1209.           goto directly_done;
  1210.         }
  1211.         }
  1212.  
  1213.       /* Here for a command that isn't executed directly */
  1214.  
  1215.       nonundocount = 0;
  1216.       if (NILP (Vprefix_arg))
  1217.         Fundo_boundary ();
  1218.       Fcommand_execute (this_command, Qnil);
  1219.  
  1220.     }
  1221.     directly_done: ;
  1222.  
  1223.       if (!NILP (Vpost_command_hook))
  1224.     call1 (Vrun_hooks, Qpost_command_hook);
  1225.  
  1226.       /* If there is a prefix argument,
  1227.      1) We don't want last_command to be ``universal-argument''
  1228.      (that would be dumb), so don't set last_command,
  1229.      2) we want to leave echoing on so that the prefix will be
  1230.      echoed as part of this key sequence, so don't call
  1231.      cancel_echoing, and
  1232.      3) we want to leave this_command_key_count non-zero, so that
  1233.      read_char will realize that it is re-reading a character, and
  1234.      not echo it a second time.  */
  1235.       if (NILP (Vprefix_arg))
  1236.     {
  1237.       last_command = this_command;
  1238.       cancel_echoing ();
  1239.       this_command_key_count = 0;
  1240.     }
  1241.  
  1242.       if (!NILP (current_buffer->mark_active))
  1243.     {
  1244.       if (!NILP (Vdeactivate_mark) && !NILP (Vtransient_mark_mode))
  1245.         {
  1246.           current_buffer->mark_active = Qnil;
  1247.           call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
  1248.         }
  1249.       else if (current_buffer != prev_buffer || MODIFF != prev_modiff)
  1250.         call1 (Vrun_hooks, intern ("activate-mark-hook"));
  1251.     }
  1252.     }
  1253. }
  1254.  
  1255. /* Number of seconds between polling for input.  */
  1256. int polling_period;
  1257.  
  1258. /* Nonzero means polling for input is temporarily suppressed.  */
  1259. int poll_suppress_count;
  1260.  
  1261. #ifdef POLL_FOR_INPUT
  1262. int polling_for_input;
  1263.  
  1264. /* Handle an alarm once each second and read pending input
  1265.    so as to handle a C-g if it comces in.  */
  1266.  
  1267. SIGTYPE
  1268. input_poll_signal ()
  1269. {
  1270.   if (interrupt_input_blocked == 0
  1271.       && !waiting_for_input)
  1272.     read_avail_input (0);
  1273.   signal (SIGALRM, input_poll_signal);
  1274.   alarm (polling_period);
  1275. }
  1276.  
  1277. #endif
  1278.  
  1279. /* Begin signals to poll for input, if they are appropriate.
  1280.    This function is called unconditionally from various places.  */
  1281.  
  1282. _VOID_
  1283. start_polling ()
  1284. {
  1285. #ifdef POLL_FOR_INPUT
  1286.   if (read_socket_hook)
  1287.     {
  1288.       poll_suppress_count--;
  1289.       if (poll_suppress_count == 0)
  1290.     {
  1291.       signal (SIGALRM, input_poll_signal);
  1292.       polling_for_input = 1;
  1293.       alarm (polling_period);
  1294.     }
  1295.     }
  1296. #endif
  1297. }
  1298.  
  1299. /* Turn off polling.  */
  1300.  
  1301. _VOID_
  1302. stop_polling ()
  1303. {
  1304. #ifdef POLL_FOR_INPUT
  1305.   if (read_socket_hook)
  1306.     {
  1307.       if (poll_suppress_count == 0)
  1308.     {
  1309.       polling_for_input = 0;
  1310.       alarm (0);
  1311.     }
  1312.       poll_suppress_count++;
  1313.     }
  1314. #endif
  1315. }
  1316.  
  1317. /* Applying the control modifier to CHARACTER.  */
  1318. int
  1319. make_ctrl_char (c)
  1320.      int c;
  1321. {
  1322.   /* Save the upper bits here.  */
  1323.   int upper = c & ~0177;
  1324.  
  1325.   c &= 0177;
  1326.  
  1327.   /* Everything in the columns containing the upper-case letters
  1328.      denotes a control character.  */
  1329.   if (c >= 0100 && c < 0140)
  1330.     {
  1331.       int oc = c;
  1332.       c &= ~0140;
  1333.       /* Set the shift modifier for a control char
  1334.      made from a shifted letter.  But only for letters!  */
  1335.       if (oc >= 'A' && oc <= 'Z')
  1336.     c |= shift_modifier;
  1337.     }
  1338.  
  1339.   /* The lower-case letters denote control characters too.  */
  1340.   else if (c >= 'a' && c <= 'z')
  1341.     c &= ~0140;
  1342.  
  1343.   /* Include the bits for control and shift
  1344.      only if the basic ASCII code can't indicate them.  */
  1345.   else if (c >= ' ')
  1346.     c |= ctrl_modifier;
  1347.  
  1348.   /* Replace the high bits.  */
  1349.   c |= (upper & ~ctrl_modifier);
  1350.  
  1351.   return c;
  1352. }
  1353.  
  1354.  
  1355.  
  1356. /* Input of single characters from keyboard */
  1357.  
  1358. /* read a character from the keyboard; call the redisplay if needed */
  1359. /* commandflag 0 means do not do auto-saving, but do do redisplay.
  1360.    -1 means do not do redisplay, but do do autosaving.
  1361.    1 means do both.  */
  1362.  
  1363. /* The arguments MAPS and NMAPS are for menu prompting.
  1364.    MAPS is an array of keymaps;  NMAPS is the length of MAPS.
  1365.  
  1366.    PREV_EVENT is the previous input event, or nil if we are reading
  1367.    the first event of a key sequence.
  1368.  
  1369.    If USED_MOUSE_MENU is non-zero, then we set *USED_MOUSE_MENU to 1
  1370.    if we used a mouse menu to read the input, or zero otherwise.  If
  1371.    USED_MOUSE_MENU is zero, *USED_MOUSE_MENU is left alone.
  1372.  
  1373.    Value is t if we showed a menu and the user rejected it.  */
  1374.  
  1375. Lisp_Object
  1376. read_char (commandflag, nmaps, maps, prev_event, used_mouse_menu)
  1377.      int commandflag;
  1378.      int nmaps;
  1379.      Lisp_Object *maps;
  1380.      Lisp_Object prev_event;
  1381.      int *used_mouse_menu;
  1382. {
  1383.   register Lisp_Object c;
  1384.   int count;
  1385.   jmp_buf save_jump;
  1386.  
  1387.   if (CONSP (unread_command_events))
  1388.     {
  1389.       c = XCONS (unread_command_events)->car;
  1390.       unread_command_events = XCONS (unread_command_events)->cdr;
  1391.  
  1392.       if (this_command_key_count == 0)
  1393.     goto reread_first;
  1394.       else
  1395.     goto reread;
  1396.     }
  1397.  
  1398.   if (unread_command_char != -1)
  1399.     {
  1400.       XSET (c, Lisp_Int, unread_command_char);
  1401.       unread_command_char = -1;
  1402.  
  1403.       if (this_command_key_count == 0)
  1404.     goto reread_first;
  1405.       else
  1406.     goto reread;
  1407.     }
  1408.  
  1409.   if (!NILP (Vexecuting_macro))
  1410.     {
  1411. #ifdef MULTI_FRAME
  1412.       /* We set this to Qmacro; since that's not a frame, nobody will
  1413.      try to switch frames on us, and the selected window will
  1414.      remain unchanged.
  1415.  
  1416.          Since this event came from a macro, it would be misleading to
  1417.      leave internal_last_event_frame set to wherever the last
  1418.      real event came from.  Normally, a switch-frame event selects
  1419.      internal_last_event_frame after each command is read, but
  1420.      events read from a macro should never cause a new frame to be
  1421.      selected. */
  1422.       Vlast_event_frame = internal_last_event_frame = Qmacro;
  1423. #endif
  1424.  
  1425.       /* Exit the macro if we are at the end.
  1426.      Also, some things replace the macro with t
  1427.      to force an early exit.  */
  1428.       if (EQ (Vexecuting_macro, Qt)
  1429.       || executing_macro_index >= XFASTINT (Flength (Vexecuting_macro)))
  1430.     {
  1431.       XSET (c, Lisp_Int, -1);
  1432.       return c;
  1433.     }
  1434.       
  1435.       c = Faref (Vexecuting_macro, make_number (executing_macro_index));
  1436.       if (XTYPE (Vexecuting_macro) == Lisp_String
  1437.       && (XINT (c) & 0x80))
  1438.     XFASTINT (c) = CHAR_META | (XINT (c) & ~0x80);
  1439.  
  1440.       executing_macro_index++;
  1441.  
  1442.       goto from_macro;
  1443.     }
  1444.  
  1445.   if (!NILP (unread_switch_frame))
  1446.     {
  1447.       c = unread_switch_frame;
  1448.       unread_switch_frame = Qnil;
  1449.  
  1450.       /* This event should make it into this_command_keys, and get echoed
  1451.      again, so we go to reread_first, rather than reread.  */
  1452.       goto reread_first;
  1453.     }
  1454.  
  1455.   /* Save outer setjmp data, in case called recursively.  */
  1456.   save_getcjmp (save_jump);
  1457.  
  1458.   stop_polling ();
  1459.  
  1460.   if (commandflag >= 0 && !input_pending && !detect_input_pending ())
  1461.     redisplay ();
  1462.  
  1463.   if (_setjmp (getcjmp))
  1464.     {
  1465.       XSET (c, Lisp_Int, quit_char);
  1466. #ifdef MULTI_FRAME
  1467.       XSET (internal_last_event_frame, Lisp_Frame, selected_frame);
  1468.       Vlast_event_frame = internal_last_event_frame;
  1469. #endif
  1470.       /* If we report the quit char as an event,
  1471.      don't do so more than once.  */
  1472.       if (!NILP (Vinhibit_quit))
  1473.     Vquit_flag = Qnil;
  1474.  
  1475.       goto non_reread;
  1476.     }
  1477.  
  1478.   /* Message turns off echoing unless more keystrokes turn it on again. */
  1479.   if (echo_area_glyphs && *echo_area_glyphs && echo_area_glyphs != echobuf)
  1480.     cancel_echoing ();
  1481.   else
  1482.     /* If already echoing, continue.  */
  1483.     echo_dash ();
  1484.  
  1485.   /* If in middle of key sequence and minibuffer not active,
  1486.      start echoing if enough time elapses.  */
  1487.   if (minibuf_level == 0 && !immediate_echo && this_command_key_count > 0
  1488.       && echo_keystrokes > 0
  1489.       && (echo_area_glyphs == 0 || *echo_area_glyphs == 0))
  1490.     {
  1491.       Lisp_Object tem0;
  1492.  
  1493.       /* After a mouse event, start echoing right away.
  1494.      This is because we are probably about to display a menu,
  1495.      and we don't want to delay before doing so.  */
  1496.       if (EVENT_HAS_PARAMETERS (prev_event))
  1497.     echo ();
  1498.       else
  1499.     {
  1500.       tem0 = sit_for (echo_keystrokes, 0, 1, 1);
  1501.       if (EQ (tem0, Qt))
  1502.         echo ();
  1503.     }
  1504.     }
  1505.  
  1506.   /* Maybe auto save due to number of keystrokes or idle time.  */
  1507.  
  1508.   if (commandflag != 0
  1509.       && auto_save_interval > 0
  1510.       && num_nonmacro_input_chars - last_auto_save > max (auto_save_interval, 20)
  1511.       && !detect_input_pending ())
  1512.     {
  1513.       jmp_buf temp;
  1514.       save_getcjmp (temp);
  1515.       Fdo_auto_save (Qnil, Qnil);
  1516.       restore_getcjmp (temp);
  1517.     }
  1518.  
  1519.   /* Try reading a character via menu prompting.
  1520.      Try this before the sit-for, because the sit-for
  1521.      would do the wrong thing if we are supposed to do
  1522.      menu prompting.  */
  1523.   c = Qnil;
  1524.   if (INTERACTIVE && !NILP (prev_event))
  1525.     c = read_char_menu_prompt (nmaps, maps, prev_event, used_mouse_menu);
  1526.  
  1527.   /* Slow down auto saves logarithmically in size of current buffer,
  1528.      and garbage collect while we're at it.  */
  1529.   if (INTERACTIVE && NILP (c))
  1530.     {
  1531.       int delay_level, buffer_size;
  1532.  
  1533.       if (! MINI_WINDOW_P (XWINDOW (selected_window)))
  1534.     last_non_minibuf_size = Z - BEG;
  1535.       buffer_size = (last_non_minibuf_size >> 8) + 1;
  1536.       delay_level = 0;
  1537.       while (buffer_size > 64)
  1538.     delay_level++, buffer_size -= buffer_size >> 2;
  1539.       if (delay_level < 4) delay_level = 4;
  1540.       /* delay_level is 4 for files under around 50k, 7 at 100k,
  1541.      9 at 200k, 11 at 300k, and 12 at 500k.  It is 15 at 1 meg.  */
  1542.  
  1543.       /* Auto save if enough time goes by without input.  */
  1544.       if (commandflag != 0
  1545.       && num_nonmacro_input_chars > last_auto_save
  1546.       && XTYPE (Vauto_save_timeout) == Lisp_Int
  1547.       && XINT (Vauto_save_timeout) > 0)
  1548.     {
  1549.       Lisp_Object tem0;
  1550.       int delay = delay_level * XFASTINT (Vauto_save_timeout) / 4;
  1551.       tem0 = sit_for (delay, 0, 1, 1);
  1552.       if (EQ (tem0, Qt))
  1553.         {
  1554.           jmp_buf temp;
  1555.           save_getcjmp (temp);
  1556.           Fdo_auto_save (Qnil, Qnil);
  1557.           restore_getcjmp (temp);
  1558.  
  1559.           /* If we have auto-saved and there is still no input
  1560.          available, garbage collect if there has been enough
  1561.          consing going on to make it worthwhile.  */
  1562.           if (!detect_input_pending ()
  1563.           && consing_since_gc > gc_cons_threshold / 2)
  1564.         {
  1565.           Fgarbage_collect ();
  1566.           redisplay ();
  1567.         }
  1568.         }
  1569.     }
  1570.     }
  1571.  
  1572.   /* Actually read a character, waiting if necessary.  */
  1573.   while (NILP (c))
  1574.     {
  1575.       c = kbd_buffer_get_event ();
  1576.       if (!NILP (c))
  1577.     break;
  1578.       if (commandflag >= 0 && !input_pending && !detect_input_pending ())
  1579.     redisplay ();
  1580.     }
  1581.  
  1582.   /* Terminate Emacs in batch mode if at eof.  */
  1583.   if (noninteractive && XTYPE (c) == Lisp_Int && XINT (c) < 0)
  1584.     Fkill_emacs (make_number (1));
  1585.  
  1586.   if (XTYPE (c) == Lisp_Int)
  1587.     {
  1588.       /* Add in any extra modifiers, where appropriate.  */
  1589.       if ((extra_keyboard_modifiers & CHAR_CTL)
  1590.       || ((extra_keyboard_modifiers & 0177) < ' '
  1591.           && (extra_keyboard_modifiers & 0177) != 0))
  1592.     XSETINT (c, make_ctrl_char (XINT (c)));
  1593.  
  1594.       /* Transfer any other modifier bits directly from
  1595.      extra_keyboard_modifiers to c.  Ignore the actual character code
  1596.      in the low 16 bits of extra_keyboard_modifiers.  */
  1597.       XSETINT (c, XINT (c) | (extra_keyboard_modifiers & ~0xff7f & ~CHAR_CTL));
  1598.     }
  1599.  
  1600.  non_reread:
  1601.  
  1602.   restore_getcjmp (save_jump);
  1603.  
  1604.   start_polling ();
  1605.  
  1606.   echo_area_glyphs = 0;
  1607.  
  1608.   /* Handle things that only apply to characters.  */
  1609.   if (XTYPE (c) == Lisp_Int)
  1610.     {
  1611.       /* If kbd_buffer_get_event gave us an EOF, return that.  */
  1612.       if (XINT (c) == -1)
  1613.     return c;
  1614.  
  1615.       if (XTYPE (Vkeyboard_translate_table) == Lisp_String
  1616.       && XSTRING (Vkeyboard_translate_table)->size > XFASTINT (c))
  1617.     XSETINT (c, XSTRING (Vkeyboard_translate_table)->data[XFASTINT (c)]);
  1618.     }
  1619.  
  1620.   total_keys++;
  1621.   XVECTOR (recent_keys)->contents[recent_keys_index] = c;
  1622.   if (++recent_keys_index >= NUM_RECENT_KEYS)
  1623.     recent_keys_index = 0;
  1624.  
  1625.   /* Write c to the dribble file.  If c is a lispy event, write
  1626.      the event's symbol to the dribble file, in <brackets>.  Bleaugh.
  1627.      If you, dear reader, have a better idea, you've got the source.  :-) */
  1628.   if (dribble)
  1629.     {
  1630.       if (XTYPE (c) == Lisp_Int)
  1631.     putc (XINT (c), dribble);
  1632.       else
  1633.     {
  1634.       Lisp_Object dribblee = c;
  1635.  
  1636.       /* If it's a structured event, take the event header.  */
  1637.       dribblee = EVENT_HEAD (dribblee);
  1638.  
  1639.       if (XTYPE (dribblee) == Lisp_Symbol)
  1640.         {
  1641.           putc ('<', dribble);
  1642.           fwrite (XSYMBOL (dribblee)->name->data, sizeof (char),
  1643.               XSYMBOL (dribblee)->name->size,
  1644.               dribble);
  1645.           putc ('>', dribble);
  1646.         }
  1647.     }
  1648.  
  1649.       fflush (dribble);
  1650.     }
  1651.  
  1652.   store_kbd_macro_char (c);
  1653.  
  1654.   num_nonmacro_input_chars++;
  1655.  
  1656.  from_macro:
  1657.  reread_first:
  1658.  
  1659.   /* Record this character as part of the current key.
  1660.      Don't record mouse motion; it should never matter.  */
  1661.   if (! (EVENT_HAS_PARAMETERS (c)
  1662.      && EQ (EVENT_HEAD_KIND (EVENT_HEAD (c)), Qmouse_movement)))
  1663.     {
  1664.       echo_char (c);
  1665.       add_command_key (c);
  1666.     }
  1667.  
  1668.   /* Re-reading in the middle of a command */
  1669.  reread:
  1670.   last_input_char = c;
  1671.   num_input_chars++;
  1672.  
  1673.   /* Process the help character specially if enabled */
  1674.   if (EQ (c, Vhelp_char) && !NILP (Vhelp_form))
  1675.     {
  1676.       Lisp_Object tem0;
  1677.       count = specpdl_ptr - specpdl;
  1678.  
  1679.       record_unwind_protect (Fset_window_configuration,
  1680.                  Fcurrent_window_configuration (Qnil));
  1681.  
  1682.       tem0 = Feval (Vhelp_form);
  1683.       if (XTYPE (tem0) == Lisp_String)
  1684.     internal_with_output_to_temp_buffer ("*Help*", print_help, tem0);
  1685.  
  1686.       cancel_echoing ();
  1687.       c = read_char (0, 0, 0, Qnil, 0);
  1688.       /* Remove the help from the frame */
  1689.       unbind_to (count, Qnil);
  1690.       redisplay ();
  1691.       if (EQ (c, make_number (040)))
  1692.     {
  1693.       cancel_echoing ();
  1694.       c = read_char (0, 0, 0, Qnil, 0);
  1695.     }
  1696.     }
  1697.  
  1698.   return c;
  1699. }
  1700.  
  1701. Lisp_Object
  1702. print_help (object)
  1703.      Lisp_Object object;
  1704. {
  1705.   Fprinc (object, Qnil);
  1706.   return Qnil;
  1707. }
  1708.  
  1709. /* Copy out or in the info on where C-g should throw to.
  1710.    This is used when running Lisp code from within get_char,
  1711.    in case get_char is called recursively.
  1712.    See read_process_output.  */
  1713.  
  1714. _VOID_
  1715. save_getcjmp (temp)
  1716.      jmp_buf temp;
  1717. {
  1718.   bcopy (getcjmp, temp, sizeof getcjmp);
  1719. }
  1720.  
  1721. _VOID_
  1722. restore_getcjmp (temp)
  1723.      jmp_buf temp;
  1724. {
  1725.   bcopy (temp, getcjmp, sizeof getcjmp);
  1726. }
  1727.  
  1728.  
  1729. /* Low level keyboard/mouse input.
  1730.    kbd_buffer_store_event places events in kbd_buffer, and
  1731.    kbd_buffer_get_event retrieves them.
  1732.    mouse_moved indicates when the mouse has moved again, and
  1733.    *mouse_position_hook provides the mouse position.  */
  1734.  
  1735. /* Set this for debugging, to have a way to get out */
  1736. int stop_character;
  1737.  
  1738. extern int frame_garbaged;
  1739.  
  1740. /* Return true iff there are any events in the queue that read-char
  1741.    would return.  If this returns false, a read-char would block.  */
  1742. static int
  1743. readable_events ()
  1744. {
  1745.   return ! EVENT_QUEUES_EMPTY;
  1746. }
  1747.  
  1748.  
  1749. /* Restore mouse tracking enablement.  See Ftrack_mouse for the only use
  1750.    of this function.  */
  1751. static Lisp_Object
  1752. tracking_off (old_value)
  1753.      Lisp_Object old_value;
  1754. {
  1755.   if (! XFASTINT (old_value))
  1756.     {
  1757.       do_mouse_tracking = 0;
  1758.  
  1759.       /* Redisplay may have been preempted because there was input
  1760.      available, and it assumes it will be called again after the
  1761.      input has been processed.  If the only input available was
  1762.      the sort that we have just disabled, then we need to call
  1763.      redisplay.  */
  1764.       if (!readable_events ())
  1765.     {
  1766.       redisplay_preserve_echo_area ();
  1767.       get_input_pending (&input_pending);
  1768.     }
  1769.     }
  1770.   return Qt;
  1771. }
  1772.  
  1773. DEFUN ("track-mouse", Ftrack_mouse, Strack_mouse, 0, UNEVALLED, 0,
  1774.   "Evaluate BODY with mouse movement events enabled.\n\
  1775. Within a `track-mouse' form, mouse motion generates input events that\n\
  1776. you can read with `read-event'.\n\
  1777. Normally, mouse motion is ignored.")
  1778.   (args)
  1779.      Lisp_Object args;
  1780. {
  1781.   int count = specpdl_ptr - specpdl;
  1782.   Lisp_Object val;
  1783.  
  1784.   XSET (val, Lisp_Int, do_mouse_tracking);
  1785.   record_unwind_protect (tracking_off, val);
  1786.  
  1787.   do_mouse_tracking = 1;
  1788.   
  1789.   val = Fprogn (args);
  1790.   return unbind_to (count, val);
  1791. }
  1792.  
  1793. /* Store an event obtained at interrupt level into kbd_buffer, fifo */
  1794.  
  1795. void
  1796. kbd_buffer_store_event (event)
  1797.      register struct input_event *event;
  1798. {
  1799.   if (event->kind == no_event)
  1800.     abort ();
  1801.  
  1802.   if (event->kind == ascii_keystroke)
  1803.     {
  1804.       register int c = XFASTINT (event->code) & 0377;
  1805.  
  1806.       if (event->modifiers & ctrl_modifier)
  1807.     c = make_ctrl_char (c);
  1808.  
  1809.       if (c == quit_char)
  1810.     {
  1811. #ifndef USE_PROTOTYPES
  1812.       extern SIGTYPE interrupt_signal ();
  1813. #endif
  1814.  
  1815. #ifdef MULTI_FRAME
  1816.       /* If this results in a quit_char being returned to Emacs as
  1817.          input, set Vlast_event_frame properly.  If this doesn't
  1818.          get returned to Emacs as an event, the next event read
  1819.          will set Vlast_event_frame again, so this is safe to do.  */
  1820.       {
  1821.         Lisp_Object focus =
  1822.           FRAME_FOCUS_FRAME (XFRAME (event->frame_or_window));
  1823.  
  1824.         if (NILP (focus))
  1825.           internal_last_event_frame = event->frame_or_window;
  1826.         else
  1827.           internal_last_event_frame = focus;
  1828.         Vlast_event_frame = internal_last_event_frame;
  1829.       }
  1830. #endif
  1831.  
  1832.       last_event_timestamp = event->timestamp;
  1833.       interrupt_signal ();
  1834.       return;
  1835.     }
  1836.  
  1837.       if (c && c == stop_character)
  1838.     {
  1839.       sys_suspend ();
  1840.       return;
  1841.     }
  1842.  
  1843.       XSET (event->code, Lisp_Int, c);
  1844.     }
  1845.  
  1846.   if (kbd_store_ptr - kbd_buffer == KBD_BUFFER_SIZE)
  1847.     kbd_store_ptr = kbd_buffer;
  1848.  
  1849.   /* Don't let the very last slot in the buffer become full,
  1850.      since that would make the two pointers equal,
  1851.      and that is indistinguishable from an empty buffer.
  1852.      Discard the event if it would fill the last slot.  */
  1853.   if (kbd_fetch_ptr - 1 != kbd_store_ptr)
  1854.     {
  1855.       kbd_store_ptr->kind = event->kind;
  1856.       kbd_store_ptr->code = event->code;
  1857.       kbd_store_ptr->part = event->part;
  1858.       kbd_store_ptr->frame_or_window = event->frame_or_window;
  1859.       kbd_store_ptr->modifiers = event->modifiers;
  1860.       kbd_store_ptr->x = event->x;
  1861.       kbd_store_ptr->y = event->y;
  1862.       kbd_store_ptr->timestamp = event->timestamp;
  1863.       (XVECTOR (kbd_buffer_frame_or_window)->contents[kbd_store_ptr
  1864.                               - kbd_buffer]
  1865.        = event->frame_or_window);
  1866.  
  1867.       kbd_store_ptr++;
  1868.     }
  1869. }
  1870.  
  1871. static Lisp_Object
  1872. kbd_buffer_get_event ()
  1873. {
  1874.   register int c;
  1875.   Lisp_Object obj;
  1876.  
  1877.   if (noninteractive)
  1878.     {
  1879.       c = getchar ();
  1880.       XSET (obj, Lisp_Int, c);
  1881.       return obj;
  1882.     }
  1883.  
  1884. #if 0
  1885.  retry:
  1886. #endif
  1887.   /* Wait until there is input available.  */
  1888.   for (;;)
  1889.     {
  1890.       if (!EVENT_QUEUES_EMPTY)
  1891.     break;
  1892.  
  1893.       /* If the quit flag is set, then read_char will return
  1894.      quit_char, so that counts as "available input."  */
  1895.       if (!NILP (Vquit_flag))
  1896.     quit_throw_to_read_char ();
  1897.  
  1898.       /* One way or another, wait until input is available; then, if
  1899.      interrupt handlers have not read it, read it now.  */
  1900.  
  1901. #ifdef OLDVMS
  1902.       wait_for_kbd_input ();
  1903. #else
  1904. /* Note SIGIO has been undef'd if FIONREAD is missing.  */
  1905. #ifdef SIGIO
  1906.       gobble_input (0);
  1907. #endif /* SIGIO */
  1908.       if (EVENT_QUEUES_EMPTY)
  1909.     {
  1910.       Lisp_Object minus_one;
  1911.  
  1912.       XSET (minus_one, Lisp_Int, -1);
  1913.       wait_reading_process_input (0, 0, minus_one, 1);
  1914.  
  1915.       if (!interrupt_input && EVENT_QUEUES_EMPTY)
  1916.         {
  1917.           read_avail_input (0);
  1918.         }
  1919.     }
  1920. #endif /* not VMS */
  1921.     }
  1922.  
  1923.   /* At this point, we know that there is a readable event available
  1924.      somewhere.  If the event queue is empty, then there must be a
  1925.      mouse movement enabled and available.  */
  1926.   if (kbd_fetch_ptr != kbd_store_ptr)
  1927.     {
  1928.       struct input_event *event;
  1929.  
  1930.       event = ((kbd_fetch_ptr < kbd_buffer + KBD_BUFFER_SIZE)
  1931.            ? kbd_fetch_ptr
  1932.            : kbd_buffer);
  1933.  
  1934.       last_event_timestamp = event->timestamp;
  1935.  
  1936.       obj = Qnil;
  1937.  
  1938.       /* These two kinds of events get special handling
  1939.      and don't actually appear to the command loop.  */
  1940.       if (event->kind == selection_request_event)
  1941.     {
  1942. #ifdef HAVE_X11
  1943.       x_handle_selection_request (event);
  1944.       kbd_fetch_ptr = event + 1;
  1945. #else
  1946.       /* We're getting selection request events, but we don't have
  1947.              a window system.  */
  1948.       abort ();
  1949. #endif
  1950.     }
  1951.  
  1952.       else if (event->kind == selection_clear_event)
  1953.     {
  1954. #ifdef HAVE_X11
  1955.       x_handle_selection_clear (event);
  1956.       kbd_fetch_ptr = event + 1;
  1957. #else
  1958.       /* We're getting selection request events, but we don't have
  1959.              a window system.  */
  1960.       abort ();
  1961. #endif
  1962.     }
  1963.  
  1964.       /* If this event is on a different frame, return a switch-frame this
  1965.      time, and leave the event in the queue for next time.  */
  1966.       else
  1967.     {
  1968. #ifdef MULTI_FRAME
  1969.       Lisp_Object frame = event->frame_or_window;
  1970.       Lisp_Object focus;
  1971.  
  1972.       if (XTYPE (frame) == Lisp_Window)
  1973.         frame = WINDOW_FRAME (XWINDOW (frame));
  1974.  
  1975.       focus = FRAME_FOCUS_FRAME (XFRAME (frame));
  1976.       if (! NILP (focus))
  1977.         frame = focus;
  1978.  
  1979.       if (! EQ (frame, internal_last_event_frame)
  1980.           && XFRAME (frame) != selected_frame)
  1981.         obj = make_lispy_switch_frame (frame);
  1982.       internal_last_event_frame = frame;
  1983. #endif /* MULTI_FRAME */
  1984.  
  1985.       /* If we didn't decide to make a switch-frame event, go ahead
  1986.          and build a real event from the queue entry.  */
  1987.  
  1988.       if (NILP (obj))
  1989.         {
  1990.           obj = make_lispy_event (event);
  1991.  
  1992.           /* Wipe out this event, to catch bugs.  */
  1993.           event->kind = no_event;
  1994.           (XVECTOR (kbd_buffer_frame_or_window)->contents[event - kbd_buffer]
  1995.            = Qnil);
  1996.  
  1997.           kbd_fetch_ptr = event + 1;
  1998.         }
  1999.     }
  2000.     }
  2001.   else if (do_mouse_tracking && mouse_moved)
  2002.     {
  2003.       FRAME_PTR f = 0;
  2004.       Lisp_Object bar_window;
  2005.       enum scroll_bar_part part;
  2006.       Lisp_Object x, y;
  2007.       unsigned long time;
  2008.  
  2009.       (*mouse_position_hook) (&f, &bar_window, &part, &x, &y, &time);
  2010.  
  2011.       obj = Qnil;
  2012.  
  2013. #ifdef MULTI_FRAME
  2014.       /* Decide if we should generate a switch-frame event.  Don't
  2015.      generate switch-frame events for motion outside of all Emacs
  2016.      frames.  */
  2017.       if (f)
  2018.     {
  2019.       Lisp_Object frame = FRAME_FOCUS_FRAME (f);
  2020.  
  2021.       if (NILP (frame))
  2022.         XSET (frame, Lisp_Frame, f);
  2023.  
  2024.       if (! EQ (frame, internal_last_event_frame)
  2025.           && XFRAME (frame) != selected_frame)
  2026.         obj = make_lispy_switch_frame (frame);
  2027.       internal_last_event_frame = frame;
  2028.     }
  2029. #endif
  2030.  
  2031.       /* If we didn't decide to make a switch-frame event, go ahead and 
  2032.      return a mouse-motion event.  */
  2033.       if (NILP (obj))
  2034.     obj = make_lispy_movement (f, bar_window, part, x, y, time);
  2035.      }
  2036.   else
  2037.     /* We were promised by the above while loop that there was
  2038.        something for us to read!  */
  2039.     abort ();
  2040.  
  2041. #if 0
  2042.   /* If something gave back nil as the Lispy event,
  2043.      it means the event was discarded, so try again.  */
  2044.   if (NILP (obj))
  2045.     goto retry;
  2046. #endif
  2047.  
  2048.   input_pending = readable_events ();
  2049.  
  2050. #ifdef MULTI_FRAME
  2051.   Vlast_event_frame = internal_last_event_frame;
  2052. #endif
  2053.  
  2054.   return (obj);
  2055. }
  2056.  
  2057. /* Process any events that are not user-visible.  */
  2058.  
  2059. void
  2060. swallow_events ()
  2061. {
  2062.   while (kbd_fetch_ptr != kbd_store_ptr)
  2063.     {
  2064.       struct input_event *event;
  2065.  
  2066.       event = ((kbd_fetch_ptr < kbd_buffer + KBD_BUFFER_SIZE)
  2067.            ? kbd_fetch_ptr
  2068.            : kbd_buffer);
  2069.  
  2070.       last_event_timestamp = event->timestamp;
  2071.  
  2072.       /* These two kinds of events get special handling
  2073.      and don't actually appear to the command loop.  */
  2074.       if (event->kind == selection_request_event)
  2075.     {
  2076. #ifdef HAVE_X11
  2077.       x_handle_selection_request (event);
  2078.       kbd_fetch_ptr = event + 1;
  2079. #else
  2080.       /* We're getting selection request events, but we don't have
  2081.              a window system.  */
  2082.       abort ();
  2083. #endif
  2084.     }
  2085.  
  2086.       else if (event->kind == selection_clear_event)
  2087.     {
  2088. #ifdef HAVE_X11
  2089.       x_handle_selection_clear (event);
  2090.       kbd_fetch_ptr = event + 1;
  2091. #else
  2092.       /* We're getting selection request events, but we don't have
  2093.              a window system.  */
  2094.       abort ();
  2095. #endif
  2096.     }
  2097.       else
  2098.     break;
  2099.     }
  2100.  
  2101.   get_input_pending (&input_pending);
  2102. }
  2103.  
  2104. /* Caches for modify_event_symbol.  */
  2105. static Lisp_Object func_key_syms;
  2106. static Lisp_Object mouse_syms;
  2107.  
  2108. /* You'll notice that this table is arranged to be conveniently
  2109.    indexed by X Windows keysym values.  */
  2110. static char *lispy_function_keys[] =
  2111.   {
  2112.     /* X Keysym value */
  2113.  
  2114.     "remove", 0, 0, 0, 0, 0, 0, 0,    /* 0xff00 */
  2115.     "backspace",
  2116.     "tab",
  2117.     "linefeed",
  2118.     "clear",
  2119.     0,
  2120.     "return",
  2121.     0, 0,
  2122.     0, 0, 0,            /* 0xff10 */
  2123.     "pause",
  2124.     0, 0, 0, 0, 0, 0, 0,
  2125.     "escape",
  2126.     0, 0, 0, 0,
  2127.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   /* 0xff20...2f */
  2128.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   /* 0xff30...3f */
  2129.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   /* 0xff40...4f */
  2130.  
  2131.     "home",            /* 0xff50 */    /* IsCursorKey */
  2132.     "left",
  2133.     "up",
  2134.     "right",
  2135.     "down",
  2136.     "prior",
  2137.     "next",
  2138.     "end",
  2139.     "begin",
  2140.     0,                /* 0xff59 */
  2141.     0, 0, 0, 0, 0, 0,
  2142.     "select",            /* 0xff60 */    /* IsMiscFunctionKey */
  2143.     "print",
  2144.     "execute",
  2145.     "insert",
  2146.     0,        /* 0xff64 */
  2147.     "undo",
  2148.     "redo",
  2149.     "menu",
  2150.     "find",
  2151.     "cancel",
  2152.     "help",
  2153.     "break",            /* 0xff6b */
  2154.  
  2155.     /* Here are some keys found mostly on HP keyboards.  The X event
  2156.        handling code will strip bit 29, which flags vendor-specific
  2157.        keysyms.  */
  2158.     "reset",            /* 0x1000ff6c */
  2159.     "system",
  2160.     "user",
  2161.     "clearline",
  2162.     "insertline",
  2163.     "deleteline",
  2164.     "insertchar",
  2165.     "deletechar",
  2166.     "backtab",
  2167.     "kp-backtab",        /* 0x1000ff75 */
  2168.     0,                /* 0xff76 */
  2169.     0, 0, 0, 0, 0, 0, 0, 0, "kp-numlock",    /* 0xff7f */
  2170.     "kp-space",            /* 0xff80 */    /* IsKeypadKey */
  2171.     0, 0, 0, 0, 0, 0, 0, 0,
  2172.     "kp-tab",            /* 0xff89 */
  2173.     0, 0, 0,
  2174.     "kp-enter",            /* 0xff8d */
  2175.     0, 0, 0,
  2176.     "kp-f1",            /* 0xff91 */
  2177.     "kp-f2",
  2178.     "kp-f3",
  2179.     "kp-f4",
  2180.     0,        /* 0xff95 */
  2181.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2182.     "kp-multiply",        /* 0xffaa */
  2183.     "kp-add",
  2184.     "kp-separator",
  2185.     "kp-subtract",
  2186.     "kp-decimal",
  2187.     "kp-divide",        /* 0xffaf */
  2188.     "kp-0",            /* 0xffb0 */
  2189.     "kp-1",    "kp-2",    "kp-3",    "kp-4",    "kp-5",    "kp-6",    "kp-7",    "kp-8",    "kp-9",
  2190.     0,        /* 0xffba */
  2191.     0, 0,
  2192.     "kp-equal",            /* 0xffbd */
  2193.     "f1",            /* 0xffbe */    /* IsFunctionKey */
  2194.     "f2",
  2195.     "f3", "f4", "f5", "f6", "f7", "f8",    "f9", "f10", /* 0xffc0 */
  2196.     "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18",
  2197.     "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", /* 0xffd0 */
  2198.     "f27", "f28", "f29", "f30", "f31", "f32", "f33", "f34",
  2199.     "f35", 0, 0, 0, 0, 0, 0, 0,    /* 0xffe0 */
  2200.     0, 0, 0, 0, 0, 0, 0, 0,
  2201.     0, 0, 0, 0, 0, 0, 0, 0,     /* 0xfff0 */
  2202.     0, 0, 0, 0, 0, 0, 0, "delete"
  2203.     };
  2204.  
  2205. static char *lispy_mouse_names[] = 
  2206. {
  2207.   "mouse-1", "mouse-2", "mouse-3", "mouse-4", "mouse-5"
  2208. };
  2209.  
  2210. /* Scroll bar parts.  */
  2211. Lisp_Object Qabove_handle, Qhandle, Qbelow_handle;
  2212.  
  2213. /* An array of scroll bar parts, indexed by an enum scroll_bar_part value.  */
  2214. Lisp_Object *scroll_bar_parts[] = {
  2215.   &Qabove_handle, &Qhandle, &Qbelow_handle
  2216. };
  2217.  
  2218.  
  2219. /* A vector, indexed by button number, giving the down-going location
  2220.    of currently depressed buttons, both scroll bar and non-scroll bar.
  2221.  
  2222.    The elements have the form
  2223.      (BUTTON-NUMBER MODIFIER-MASK . REST)
  2224.    where REST is the cdr of a position as it would be reported in the event.
  2225.  
  2226.    The make_lispy_event function stores positions here to tell the
  2227.    difference between click and drag events, and to store the starting
  2228.    location to be included in drag events.  */
  2229.  
  2230. static Lisp_Object button_down_location;
  2231.  
  2232. /* Information about the most recent up-going button event:  Which
  2233.    button, what location, and what time. */
  2234.  
  2235. static int button_up_button;
  2236. static int button_up_x;
  2237. static int button_up_y;
  2238. static unsigned long button_up_time;
  2239.  
  2240. /* The maximum time between clicks to make a double-click,
  2241.    or Qnil to disable double-click detection,
  2242.    or Qt for no time limit.  */
  2243. Lisp_Object Vdouble_click_time;
  2244.  
  2245. /* The number of clicks in this multiple-click. */
  2246.  
  2247. int double_click_count;
  2248.  
  2249. /* Given a struct input_event, build the lisp event which represents
  2250.    it.  If EVENT is 0, build a mouse movement event from the mouse
  2251.    movement buffer, which should have a movement event in it.
  2252.  
  2253.    Note that events must be passed to this function in the order they
  2254.    are received; this function stores the location of button presses
  2255.    in order to build drag events when the button is released.  */
  2256.  
  2257. static Lisp_Object
  2258. make_lispy_event (event)
  2259.      struct input_event *event;
  2260. {
  2261. #ifdef SWITCH_ENUM_BUG
  2262.   switch ((int) event->kind)
  2263. #else
  2264.   switch (event->kind)
  2265. #endif
  2266.     {
  2267.       /* A simple keystroke.  */
  2268.     case ascii_keystroke:
  2269.       {
  2270.     int c = XFASTINT (event->code);
  2271.     /* Turn ASCII characters into control characters
  2272.        when proper.  */
  2273.     if (event->modifiers & ctrl_modifier)
  2274.       c = make_ctrl_char (c);
  2275.  
  2276.     /* Add in the other modifier bits.  We took care of ctrl_modifier
  2277.        just above, and the shift key was taken care of by the X code,
  2278.        and applied to control characters by make_ctrl_char.  */
  2279.     c |= (event->modifiers
  2280.           & (meta_modifier | alt_modifier
  2281.          | hyper_modifier | super_modifier));
  2282.     button_up_time = 0;
  2283.     return c;
  2284.       }
  2285.  
  2286.       /* A function key.  The symbol may need to have modifier prefixes
  2287.      tacked onto it.  */
  2288.     case non_ascii_keystroke:
  2289.       button_up_time = 0;
  2290.       return modify_event_symbol (XFASTINT (event->code), event->modifiers,
  2291.                   Qfunction_key,
  2292.                   lispy_function_keys, &func_key_syms,
  2293.                   (sizeof (lispy_function_keys)
  2294.                    / sizeof (lispy_function_keys[0])));
  2295.       break;
  2296.  
  2297.       /* A mouse click.  Figure out where it is, decide whether it's 
  2298.          a press, click or drag, and build the appropriate structure.  */
  2299.     case mouse_click:
  2300.     case scroll_bar_click:
  2301.       {
  2302.     int button = XFASTINT (event->code);
  2303.     Lisp_Object position;
  2304.     Lisp_Object *start_pos_ptr;
  2305.     Lisp_Object start_pos;
  2306.  
  2307.     if (button < 0 || button >= NUM_MOUSE_BUTTONS)
  2308.       abort ();
  2309.  
  2310.     /* Build the position as appropriate for this mouse click.  */
  2311.     if (event->kind == mouse_click)
  2312.       {
  2313.         int part;
  2314.         FRAME_PTR f = XFRAME (event->frame_or_window);
  2315.         Lisp_Object window
  2316.           = window_from_coordinates (f, XINT (event->x), XINT (event->y),
  2317.                      &part);
  2318.         Lisp_Object posn;
  2319.  
  2320.         if (XINT (event->y) < FRAME_MENU_BAR_LINES (f))
  2321.           {
  2322.         Lisp_Object items;
  2323.         items = FRAME_MENU_BAR_ITEMS (f);
  2324.         for (; CONSP (items); items = XCONS (items)->cdr)
  2325.           {
  2326.             Lisp_Object pos, string;
  2327.             pos = Fcdr (Fcdr (Fcar (items)));
  2328.             string = Fcar (Fcdr (Fcar (items)));
  2329.             if (XINT (event->x) >= XINT (pos)
  2330.             && XINT (event->x) < XINT (pos) + XSTRING (string)->size)
  2331.               break;
  2332.           }
  2333.         position
  2334.           = Fcons (event->frame_or_window,
  2335.                Fcons (Qmenu_bar,
  2336.                   Fcons (Fcons (event->x, event->y),
  2337.                      Fcons (make_number (event->timestamp),
  2338.                         Qnil))));
  2339.  
  2340.         if (CONSP (items))
  2341.           return Fcons (Fcar (Fcar (items)),
  2342.                 Fcons (position, Qnil));
  2343.         else
  2344.           return Fcons (Qnil, Fcons (position, Qnil));
  2345.           }
  2346.         else if (XTYPE (window) != Lisp_Window)
  2347.           posn = Qnil;
  2348.         else
  2349.           {
  2350.         XSETINT (event->x, 
  2351.              (XINT (event->x) - XINT (XWINDOW (window)->left)));
  2352.         XSETINT (event->y,
  2353.              (XINT (event->y) - XINT (XWINDOW (window)->top)));
  2354.  
  2355.         if (part == 1)
  2356.           posn = Qmode_line;
  2357.         else if (part == 2)
  2358.           posn = Qvertical_line;
  2359.         else
  2360.           XSET (posn, Lisp_Int,
  2361.             buffer_posn_from_coords (XWINDOW (window),
  2362.                          XINT (event->x),
  2363.                          XINT (event->y)));
  2364.           }
  2365.  
  2366.         position
  2367.           = Fcons (window,
  2368.                Fcons (posn,
  2369.                   Fcons (Fcons (event->x, event->y),
  2370.                      Fcons (make_number (event->timestamp),
  2371.                         Qnil))));
  2372.       }
  2373.     else
  2374.       {
  2375.         Lisp_Object window = event->frame_or_window;
  2376.         Lisp_Object portion_whole = Fcons (event->x, event->y);
  2377.         Lisp_Object part = *scroll_bar_parts[(int) event->part];
  2378.  
  2379.         position =
  2380.           Fcons (window,
  2381.              Fcons (Qvertical_scroll_bar,
  2382.                 Fcons (portion_whole,
  2383.                    Fcons (make_number (event->timestamp),
  2384.                       Fcons (part,
  2385.                          Qnil)))));
  2386.       }
  2387.  
  2388.     start_pos_ptr = &XVECTOR (button_down_location)->contents[button];
  2389.  
  2390.     start_pos = *start_pos_ptr;
  2391.     *start_pos_ptr = Qnil;
  2392.  
  2393.     /* If this is a button press, squirrel away the location, so
  2394.            we can decide later whether it was a click or a drag.  */
  2395.     if (event->modifiers & down_modifier)
  2396.       *start_pos_ptr = Fcopy_alist (position);
  2397.  
  2398.     /* Now we're releasing a button - check the co-ordinates to
  2399.            see if this was a click or a drag.  */
  2400.     else if (event->modifiers & up_modifier)
  2401.       {
  2402.         /* If we did not see a down before this up,
  2403.            ignore the up.  Probably this happened because
  2404.            the down event chose a menu item.
  2405.            It would be an annoyance to treat the release
  2406.            of the button that chose the menu item
  2407.            as a separate event.  */
  2408.  
  2409.         if (XTYPE (start_pos) != Lisp_Cons)
  2410.           return Qnil;
  2411.  
  2412.         event->modifiers &= ~up_modifier;
  2413. #if 0 /* Formerly we treated an up with no down as a click event.  */
  2414.         if (XTYPE (start_pos) != Lisp_Cons)
  2415.           event->modifiers |= click_modifier;
  2416.         else
  2417. #endif
  2418.           {
  2419.         /* The third element of every position should be the (x,y)
  2420.            pair.  */
  2421.         Lisp_Object down = Fnth (make_number (2), start_pos);
  2422.  
  2423.         if (EQ (event->x, XCONS (down)->car)
  2424.             && EQ (event->y, XCONS (down)->cdr))
  2425.           {
  2426.             if (button == button_up_button
  2427.             && XINT (event->x) == button_up_x
  2428.             && XINT (event->y) == button_up_y
  2429.             && button_up_time != 0
  2430.             && (EQ (Vdouble_click_time, Qt)
  2431.                 || (INTEGERP (Vdouble_click_time)
  2432.                 && ((int)(event->timestamp - button_up_time)
  2433.                     < XINT (Vdouble_click_time)))))
  2434.               {
  2435.             double_click_count++;
  2436.             event->modifiers |= ((double_click_count > 2)
  2437.                          ? triple_modifier
  2438.                          : double_modifier);
  2439.               }
  2440.             else
  2441.               {
  2442.             double_click_count = 1;
  2443.             event->modifiers |= click_modifier;
  2444.               }
  2445.             button_up_button = button;
  2446.             button_up_x = XINT (event->x);
  2447.             button_up_y = XINT (event->y);
  2448.             button_up_time = event->timestamp;
  2449.           }
  2450.         else
  2451.           {
  2452.             button_up_time = 0;
  2453.             event->modifiers |= drag_modifier;
  2454.           }
  2455.           }
  2456.       }
  2457.     else
  2458.       /* Every mouse event should either have the down_modifier or
  2459.              the up_modifier set.  */
  2460.       abort ();
  2461.  
  2462.     {
  2463.       /* Get the symbol we should use for the mouse click.  */
  2464.       Lisp_Object head
  2465.         = modify_event_symbol (button,
  2466.                    event->modifiers,
  2467.                    Qmouse_click,
  2468.                    lispy_mouse_names, &mouse_syms,
  2469.                    (sizeof (lispy_mouse_names)
  2470.                     / sizeof (lispy_mouse_names[0])));
  2471.       
  2472.       if (event->modifiers & drag_modifier)
  2473.         return Fcons (head,
  2474.               Fcons (start_pos,
  2475.                  Fcons (position,
  2476.                     Qnil)));
  2477.       else if (event->modifiers & (double_modifier | triple_modifier))
  2478.         return Fcons (head,
  2479.               Fcons (position,
  2480.                  Fcons (make_number (double_click_count),
  2481.                     Qnil)));
  2482.       else
  2483.         return Fcons (head,
  2484.               Fcons (position,
  2485.                  Qnil));
  2486.     }
  2487.       }
  2488.  
  2489.       /* The 'kind' field of the event is something we don't recognize.  */
  2490.     default:
  2491.       abort ();
  2492.     }
  2493. }
  2494.  
  2495. static Lisp_Object
  2496. make_lispy_movement (frame, bar_window, part, x, y, time)
  2497.      FRAME_PTR frame;
  2498.      Lisp_Object bar_window;
  2499.      enum scroll_bar_part part;
  2500.      Lisp_Object x, y;
  2501.      unsigned long time;
  2502. {
  2503.   /* Is it a scroll bar movement?  */
  2504.   if (frame && ! NILP (bar_window))
  2505.     {
  2506.       Lisp_Object part_sym = *scroll_bar_parts[(int) part];
  2507.  
  2508.       return Fcons (Qscroll_bar_movement,
  2509.             (Fcons (Fcons (bar_window,
  2510.                    Fcons (Qvertical_scroll_bar,
  2511.                       Fcons (Fcons (x, y),
  2512.                          Fcons (make_number (time),
  2513.                             Fcons (part_sym,
  2514.                                    Qnil))))),
  2515.                 Qnil)));
  2516.     }
  2517.  
  2518.   /* Or is it an ordinary mouse movement?  */
  2519.   else
  2520.     {
  2521.       int area;
  2522.       Lisp_Object window =
  2523.     (frame
  2524.      ? window_from_coordinates (frame, XINT (x), XINT (y), &area)
  2525.      : Qnil);
  2526.       Lisp_Object posn;
  2527.  
  2528.       if (XTYPE (window) == Lisp_Window)
  2529.     {
  2530.        XSETINT (x, XINT (x) - XINT (XWINDOW (window)->left));
  2531.       XSETINT (y, XINT (y) - XINT (XWINDOW (window)->top));
  2532.  
  2533.       if (area == 1)
  2534.         posn = Qmode_line;
  2535.       else if (area == 2)
  2536.         posn = Qvertical_line;
  2537.       else
  2538.         XSET (posn, Lisp_Int,
  2539.           buffer_posn_from_coords (XWINDOW (window),
  2540.                        XINT (x), XINT (y)));
  2541.     }
  2542.       else
  2543.     {
  2544.       window = Qnil;
  2545.       posn = Qnil;
  2546.       XFASTINT (x) = 0;
  2547.       XFASTINT (y) = 0;
  2548.     }
  2549.  
  2550.       return Fcons (Qmouse_movement,
  2551.             Fcons (Fcons (window,
  2552.                   Fcons (posn,
  2553.                      Fcons (Fcons (x, y),
  2554.                         Fcons (make_number (time),
  2555.                                Qnil)))),
  2556.                Qnil));
  2557.     }
  2558. }
  2559.  
  2560. /* Construct a switch frame event.  */
  2561. static Lisp_Object
  2562. make_lispy_switch_frame (frame)
  2563.      Lisp_Object frame;
  2564. {
  2565.   return Fcons (Qswitch_frame, Fcons (frame, Qnil));
  2566. }
  2567.  
  2568. /* Manipulating modifiers.  */
  2569.  
  2570. /* Parse the name of SYMBOL, and return the set of modifiers it contains.
  2571.  
  2572.    If MODIFIER_END is non-zero, set *MODIFIER_END to the position in
  2573.    SYMBOL's name of the end of the modifiers; the string from this
  2574.    position is the unmodified symbol name.
  2575.  
  2576.    This doesn't use any caches.  */
  2577. static int
  2578. parse_modifiers_uncached (symbol, modifier_end)
  2579.      Lisp_Object symbol;
  2580.      int *modifier_end;
  2581. {
  2582.   struct Lisp_String *name;
  2583.   int i;
  2584.   int modifiers;
  2585.  
  2586.   CHECK_SYMBOL (symbol, 1);
  2587.   
  2588.   modifiers = 0;
  2589.   name = XSYMBOL (symbol)->name;
  2590.  
  2591.  
  2592.   for (i = 0; i+2 <= name->size; )
  2593.     switch (name->data[i])
  2594.       {
  2595. #define SINGLE_LETTER_MOD(bit)                    \
  2596.         if (name->data[i+1] != '-')                \
  2597.       goto no_more_modifiers;                \
  2598.     modifiers |= bit;                    \
  2599.     i += 2;
  2600.  
  2601.       case 'A':
  2602.     SINGLE_LETTER_MOD (alt_modifier);
  2603.     break;
  2604.  
  2605.       case 'C':
  2606.     SINGLE_LETTER_MOD (ctrl_modifier);
  2607.     break;
  2608.  
  2609.       case 'H':
  2610.     SINGLE_LETTER_MOD (hyper_modifier);
  2611.     break;
  2612.  
  2613.       case 'M':
  2614.     SINGLE_LETTER_MOD (meta_modifier);
  2615.     break;
  2616.  
  2617.       case 'S':
  2618.     SINGLE_LETTER_MOD (shift_modifier);
  2619.     break;
  2620.  
  2621.       case 's':
  2622.     SINGLE_LETTER_MOD (super_modifier);
  2623.     break;
  2624.  
  2625.       case 'd':
  2626.     if (i + 5 > name->size)
  2627.       goto no_more_modifiers;
  2628.     if (! strncmp (name->data + i, "drag-", 5))
  2629.       {
  2630.         modifiers |= drag_modifier;
  2631.         i += 5;
  2632.       }
  2633.     else if (! strncmp (name->data + i, "down-", 5))
  2634.       {
  2635.         modifiers |= down_modifier;
  2636.         i += 5;
  2637.       }
  2638.     else if (i + 7 <= name->size
  2639.          && ! strncmp (name->data + i, "double-", 7))
  2640.       {
  2641.         modifiers |= double_modifier;
  2642.         i += 7;
  2643.       }
  2644.     else
  2645.       goto no_more_modifiers;
  2646.     break;
  2647.  
  2648.       case 't':
  2649.     if (i + 7 > name->size)
  2650.       goto no_more_modifiers;
  2651.     if (! strncmp (name->data + i, "triple-", 7))
  2652.       {
  2653.         modifiers |= triple_modifier;
  2654.         i += 7;
  2655.       }
  2656.     else
  2657.       goto no_more_modifiers;
  2658.     break;
  2659.  
  2660.       default:
  2661.     goto no_more_modifiers;
  2662.  
  2663. #undef SINGLE_LETTER_MOD
  2664.       }
  2665.  no_more_modifiers:
  2666.  
  2667.   /* Should we include the `click' modifier?  */
  2668.   if (! (modifiers & (down_modifier | drag_modifier
  2669.               | double_modifier | triple_modifier))
  2670.       && i + 7 == name->size
  2671.       && strncmp (name->data + i, "mouse-", 6) == 0
  2672.       && ('0' <= name->data[i + 6] && name->data[i + 6] <= '9'))
  2673.     modifiers |= click_modifier;
  2674.  
  2675.   if (modifier_end)
  2676.     *modifier_end = i;
  2677.  
  2678.   return modifiers;
  2679. }
  2680.  
  2681.  
  2682. /* Return a symbol whose name is the modifier prefixes for MODIFIERS
  2683.    prepended to the string BASE[0..BASE_LEN-1].
  2684.    This doesn't use any caches.  */
  2685. static Lisp_Object
  2686. apply_modifiers_uncached (modifiers, base, base_len)
  2687.      int modifiers;
  2688.      char *base;
  2689.      int base_len;
  2690. {
  2691.   /* Since BASE could contain nulls, we can't use intern here; we have
  2692.      to use Fintern, which expects a genuine Lisp_String, and keeps a
  2693.      reference to it.  */
  2694.   char *new_mods =
  2695.     (char *) alloca (sizeof ("A-C-H-M-S-s-down-drag-double-triple-"));
  2696.   int mod_len;
  2697.  
  2698.   {
  2699.     char *p = new_mods;
  2700.  
  2701.     /* Only the event queue may use the `up' modifier; it should always
  2702.        be turned into a click or drag event before presented to lisp code.  */
  2703.     if (modifiers & up_modifier)
  2704.       abort ();
  2705.  
  2706.     if (modifiers & alt_modifier)   { *p++ = 'A'; *p++ = '-'; }
  2707.     if (modifiers & ctrl_modifier)  { *p++ = 'C'; *p++ = '-'; }
  2708.     if (modifiers & hyper_modifier) { *p++ = 'H'; *p++ = '-'; }
  2709.     if (modifiers & meta_modifier)  { *p++ = 'M'; *p++ = '-'; }
  2710.     if (modifiers & shift_modifier) { *p++ = 'S'; *p++ = '-'; }
  2711.     if (modifiers & super_modifier) { *p++ = 's'; *p++ = '-'; }
  2712.     if (modifiers & down_modifier)  { strcpy (p, "down-");  p += 5; }
  2713.     if (modifiers & drag_modifier)  { strcpy (p, "drag-");  p += 5; }
  2714.     if (modifiers & double_modifier)  { strcpy (p, "double-");  p += 7; }
  2715.     if (modifiers & triple_modifier)  { strcpy (p, "triple-");  p += 7; }
  2716.     /* The click modifier is denoted by the absence of other modifiers.  */
  2717.  
  2718.     *p = '\0';
  2719.  
  2720.     mod_len = p - new_mods;
  2721.   }
  2722.  
  2723.   {
  2724.     Lisp_Object new_name = make_uninit_string (mod_len + base_len);
  2725.     
  2726.     bcopy (new_mods, XSTRING (new_name)->data,           mod_len);
  2727.     bcopy (base,     XSTRING (new_name)->data + mod_len, base_len);
  2728.  
  2729.     return Fintern (new_name, Qnil);
  2730.   }
  2731. }
  2732.  
  2733.  
  2734. static char *modifier_names[] =
  2735. {
  2736.   "up", "down", "drag", "click", "double", "triple", 0, 0,
  2737.   0, 0, 0, 0, 0, 0, 0, 0,
  2738.   0, 0, "alt", "super", "hyper", "shift", "control", "meta"
  2739. };
  2740. #define NUM_MOD_NAMES (sizeof (modifier_names) / sizeof (modifier_names[0]))
  2741.  
  2742. static Lisp_Object modifier_symbols;
  2743.  
  2744. /* Return the list of modifier symbols corresponding to the mask MODIFIERS.  */
  2745. static Lisp_Object
  2746. lispy_modifier_list (modifiers)
  2747.      int modifiers;
  2748. {
  2749.   Lisp_Object modifier_list;
  2750.   int i;
  2751.  
  2752.   modifier_list = Qnil;
  2753.   for (i = 0; (1<<i) <= modifiers && i < NUM_MOD_NAMES; i++)
  2754.     if (modifiers & (1<<i))
  2755.       modifier_list = Fcons (XVECTOR (modifier_symbols)->contents[i],
  2756.                  modifier_list);
  2757.  
  2758.   return modifier_list;
  2759. }
  2760.  
  2761.  
  2762. /* Parse the modifiers on SYMBOL, and return a list like (UNMODIFIED MASK),
  2763.    where UNMODIFIED is the unmodified form of SYMBOL,
  2764.    MASK is the set of modifiers present in SYMBOL's name.
  2765.    This is similar to parse_modifiers_uncached, but uses the cache in
  2766.    SYMBOL's Qevent_symbol_element_mask property, and maintains the
  2767.    Qevent_symbol_elements property.  */
  2768. static Lisp_Object
  2769. parse_modifiers (symbol)
  2770.      Lisp_Object symbol;
  2771. {
  2772.   Lisp_Object elements = Fget (symbol, Qevent_symbol_element_mask);
  2773.  
  2774.   if (CONSP (elements))
  2775.     return elements;
  2776.   else
  2777.     {
  2778.       int end;
  2779.       int modifiers = parse_modifiers_uncached (symbol, &end);
  2780.       Lisp_Object unmodified
  2781.     = Fintern (make_string (XSYMBOL (symbol)->name->data + end,
  2782.                 XSYMBOL (symbol)->name->size - end),
  2783.            Qnil);
  2784.       Lisp_Object mask;
  2785.  
  2786.       if (modifiers & ~((1<<VALBITS) - 1))
  2787.     abort ();
  2788.       XFASTINT (mask) = modifiers;
  2789.       elements = Fcons (unmodified, Fcons (mask, Qnil));
  2790.  
  2791.       /* Cache the parsing results on SYMBOL.  */
  2792.       Fput (symbol, Qevent_symbol_element_mask,
  2793.         elements);
  2794.       Fput (symbol, Qevent_symbol_elements,
  2795.         Fcons (unmodified, lispy_modifier_list (modifiers)));
  2796.  
  2797.       /* Since we know that SYMBOL is modifiers applied to unmodified,
  2798.      it would be nice to put that in unmodified's cache.
  2799.      But we can't, since we're not sure that parse_modifiers is
  2800.      canonical.  */
  2801.  
  2802.       return elements;
  2803.     }
  2804. }
  2805.  
  2806. /* Apply the modifiers MODIFIERS to the symbol BASE.
  2807.    BASE must be unmodified.
  2808.  
  2809.    This is like apply_modifiers_uncached, but uses BASE's
  2810.    Qmodifier_cache property, if present.  It also builds
  2811.    Qevent_symbol_elements properties, since it has that info anyway.
  2812.  
  2813.    apply_modifiers copies the value of BASE's Qevent_kind property to
  2814.    the modified symbol.  */
  2815. static Lisp_Object
  2816. apply_modifiers (modifiers, base)
  2817.      int modifiers;
  2818.      Lisp_Object base;
  2819. {
  2820.   Lisp_Object cache, index, entry, new_symbol;
  2821.  
  2822.   /* Mask out upper bits.  We don't know where this value's been.  */
  2823.   modifiers &= (1<<VALBITS) - 1;
  2824.  
  2825.   /* The click modifier never figures into cache indices.  */
  2826.   cache = Fget (base, Qmodifier_cache);
  2827.   XFASTINT (index) = (modifiers & ~click_modifier);
  2828.   entry = Fassq (index, cache);
  2829.  
  2830.   if (CONSP (entry))
  2831.     new_symbol = XCONS (entry)->cdr;
  2832.   else
  2833.     {
  2834.       /* We have to create the symbol ourselves.  */  
  2835.       new_symbol = apply_modifiers_uncached (modifiers,
  2836.                          XSYMBOL (base)->name->data,
  2837.                          XSYMBOL (base)->name->size);
  2838.  
  2839.       /* Add the new symbol to the base's cache.  */
  2840.       entry = Fcons (index, new_symbol);
  2841.       Fput (base, Qmodifier_cache, Fcons (entry, cache));
  2842.  
  2843.       /* We have the parsing info now for free, so add it to the caches.  */
  2844.       XFASTINT (index) = modifiers;
  2845.       Fput (new_symbol, Qevent_symbol_element_mask,
  2846.         Fcons (base, Fcons (index, Qnil)));
  2847.       Fput (new_symbol, Qevent_symbol_elements,
  2848.         Fcons (base, lispy_modifier_list (modifiers)));
  2849.     }
  2850.  
  2851.   /* Make sure this symbol is of the same kind as BASE.  
  2852.  
  2853.      You'd think we could just set this once and for all when we
  2854.      intern the symbol above, but reorder_modifiers may call us when
  2855.      BASE's property isn't set right; we can't assume that just
  2856.      because it has a Qmodifier_cache property it must have its
  2857.      Qevent_kind set right as well.  */
  2858.   if (NILP (Fget (new_symbol, Qevent_kind)))
  2859.     {
  2860.       Lisp_Object kind = Fget (base, Qevent_kind);
  2861.  
  2862.       if (! NILP (kind))
  2863.     Fput (new_symbol, Qevent_kind, kind);
  2864.     }
  2865.  
  2866.   return new_symbol;
  2867. }
  2868.  
  2869.  
  2870. /* Given a symbol whose name begins with modifiers ("C-", "M-", etc),
  2871.    return a symbol with the modifiers placed in the canonical order.
  2872.    Canonical order is alphabetical, except for down and drag, which
  2873.    always come last.  The 'click' modifier is never written out.
  2874.  
  2875.    Fdefine_key calls this to make sure that (for example) C-M-foo
  2876.    and M-C-foo end up being equivalent in the keymap.  */
  2877.  
  2878. Lisp_Object
  2879. reorder_modifiers (symbol)
  2880.      Lisp_Object symbol;
  2881. {
  2882.   /* It's hopefully okay to write the code this way, since everything
  2883.      will soon be in caches, and no consing will be done at all.  */
  2884.   Lisp_Object parsed = parse_modifiers (symbol);
  2885.  
  2886.   return apply_modifiers (XCONS (XCONS (parsed)->cdr)->car,
  2887.               XCONS (parsed)->car);
  2888. }
  2889.  
  2890.  
  2891. /* For handling events, we often want to produce a symbol whose name
  2892.    is a series of modifier key prefixes ("M-", "C-", etcetera) attached
  2893.    to some base, like the name of a function key or mouse button.
  2894.    modify_event_symbol produces symbols of this sort.
  2895.  
  2896.    NAME_TABLE should point to an array of strings, such that NAME_TABLE[i]
  2897.    is the name of the i'th symbol.  TABLE_SIZE is the number of elements
  2898.    in the table.
  2899.  
  2900.    SYMBOL_TABLE should be a pointer to a Lisp_Object whose value will
  2901.    persist between calls to modify_event_symbol that it can use to
  2902.    store a cache of the symbols it's generated for this NAME_TABLE
  2903.    before.
  2904.  
  2905.    SYMBOL_NUM is the number of the base name we want from NAME_TABLE.
  2906.    
  2907.    MODIFIERS is a set of modifier bits (as given in struct input_events)
  2908.    whose prefixes should be applied to the symbol name.
  2909.  
  2910.    SYMBOL_KIND is the value to be placed in the event_kind property of
  2911.    the returned symbol. 
  2912.  
  2913.    The symbols we create are supposed to have an
  2914.    `event-symbol-elements' property, which lists the modifiers present
  2915.    in the symbol's name.  */
  2916.  
  2917. static Lisp_Object
  2918. modify_event_symbol (symbol_num, modifiers, symbol_kind, name_table,
  2919.                      symbol_table, table_size)
  2920.      int symbol_num;
  2921.      unsigned modifiers;
  2922.      Lisp_Object symbol_kind;
  2923.      char **name_table;
  2924.      Lisp_Object *symbol_table;
  2925.      int table_size;
  2926. {
  2927.   Lisp_Object *slot;
  2928.  
  2929.   /* Is this a request for a valid symbol?  */
  2930.   if (symbol_num < 0 || symbol_num >= table_size)
  2931.     abort ();
  2932.  
  2933.   /* If *symbol_table doesn't seem to be initialized properly, fix that.
  2934.      *symbol_table should be a lisp vector TABLE_SIZE elements long,
  2935.      where the Nth element is the symbol for NAME_TABLE[N], or nil if
  2936.      we've never used that symbol before.  */
  2937.   if (XTYPE (*symbol_table) != Lisp_Vector
  2938.       || XVECTOR (*symbol_table)->size != table_size)
  2939.     {
  2940.       Lisp_Object size;
  2941.  
  2942.       XFASTINT (size) = table_size;
  2943.       *symbol_table = Fmake_vector (size, Qnil);
  2944.     }
  2945.  
  2946.   slot = & XVECTOR (*symbol_table)->contents[symbol_num];
  2947.  
  2948.   /* Have we already used this symbol before?  */
  2949.   if (NILP (*slot))
  2950.     {
  2951.       /* No; let's create it.  */
  2952.       if (name_table[symbol_num])
  2953.     *slot = intern (name_table[symbol_num]);
  2954.       else
  2955.     {
  2956.       char buf[20];
  2957.       sprintf (buf, "key-%d", symbol_num);
  2958.       *slot = intern (buf);
  2959.     }
  2960.  
  2961.       /* Fill in the cache entries for this symbol; this also     
  2962.      builds the Qevent_symbol_elements property, which the user
  2963.      cares about.  */
  2964.       apply_modifiers (modifiers & click_modifier, *slot);
  2965.       Fput (*slot, Qevent_kind, symbol_kind);
  2966.     }
  2967.  
  2968.   /* Apply modifiers to that symbol.  */
  2969.   return apply_modifiers (modifiers, *slot);
  2970. }
  2971.  
  2972.  
  2973. /* Store into *addr a value nonzero if terminal input chars are available.
  2974.    Serves the purpose of ioctl (0, FIONREAD, addr)
  2975.    but works even if FIONREAD does not exist.
  2976.    (In fact, this may actually read some input.)  */
  2977.  
  2978. static void
  2979. get_input_pending (addr)
  2980.      int *addr;
  2981. {
  2982.   /* First of all, have we already counted some input?  */
  2983.   *addr = !NILP (Vquit_flag) || readable_events ();
  2984.  
  2985.   /* If input is being read as it arrives, and we have none, there is none.  */
  2986.   if (*addr > 0 || (interrupt_input && ! interrupts_deferred))
  2987.     return;
  2988.  
  2989.   /* Try to read some input and see how much we get.  */
  2990.   gobble_input (0);
  2991.   *addr = !NILP (Vquit_flag) || readable_events ();
  2992. }
  2993.  
  2994. /* Interface to read_avail_input, blocking SIGIO if necessary.  */
  2995.  
  2996. _VOID_
  2997. gobble_input (expected)
  2998.      int expected;
  2999. {
  3000. #ifndef VMS
  3001. #ifdef SIGIO
  3002.   if (interrupt_input)
  3003.     {
  3004.       SIGMASKTYPE mask;
  3005.       mask = sigblockx (SIGIO);
  3006.       read_avail_input (expected);
  3007. #ifndef WINDOWSNT
  3008.       sigsetmask (mask);
  3009. #endif /* !WINDOWSNT */
  3010.     }
  3011.   else
  3012. #endif
  3013.     read_avail_input (expected);
  3014. #endif
  3015. }
  3016.  
  3017. #ifndef VMS
  3018.  
  3019. /* Read any terminal input already buffered up by the system
  3020.    into the kbd_buffer, but do not wait.
  3021.  
  3022.    EXPECTED should be nonzero if the caller knows there is some input.
  3023.  
  3024.    Except on VMS, all input is read by this function.
  3025.    If interrupt_input is nonzero, this function MUST be called
  3026.    only when SIGIO is blocked.
  3027.  
  3028.    Returns the number of keyboard chars read, or -1 meaning
  3029.    this is a bad time to try to read input.  */
  3030.  
  3031. static int
  3032. read_avail_input (expected)
  3033.      int expected;
  3034. {
  3035.   struct input_event buf[KBD_BUFFER_SIZE];
  3036.   register int i;
  3037.   int nread;
  3038.  
  3039.   if (read_socket_hook)
  3040.     /* No need for FIONREAD or fcntl; just say don't wait.  */
  3041.     nread = (*read_socket_hook) (0, buf, KBD_BUFFER_SIZE, expected, expected);
  3042.   else
  3043.     {
  3044.       unsigned char cbuf[KBD_BUFFER_SIZE];
  3045.  
  3046. #ifdef FIONREAD
  3047.       /* Find out how much input is available.  */
  3048.       if (ioctl (0, FIONREAD, &nread) < 0)
  3049.     /* Formerly simply reported no input, but that sometimes led to
  3050.        a failure of Emacs to terminate.
  3051.        SIGHUP seems appropriate if we can't reach the terminal.  */
  3052.     /* ??? Is it really right to send the signal just to this process
  3053.        rather than to the whole process group?
  3054.        Perhaps on systems with FIONREAD Emacs is alone in its group.  */
  3055.     kill (getpid (), SIGHUP);
  3056.       if (nread == 0)
  3057.     return 0;
  3058.       if (nread > sizeof cbuf)
  3059.     nread = sizeof cbuf;
  3060. #else /* no FIONREAD */
  3061. #ifdef USG
  3062.       /* Read some input if available, but don't wait.  */
  3063.       nread = sizeof cbuf;
  3064.       fcntl (fileno (stdin), F_SETFL, O_NDELAY);
  3065. #else /* not USG */
  3066. #ifndef WINDOWSNT
  3067.       you lose;
  3068. #endif /* !WINDOWSNT */
  3069. #endif /* not USG */
  3070. #endif
  3071.  
  3072. #ifdef WINDOWSNT
  3073.       /* read_socket_hook is now provided for NT */
  3074. #if 0
  3075.       nread = read_nt_keyboard(cbuf, KBD_BUFFER_SIZE);
  3076. #else
  3077.       nread = 0;
  3078. #endif
  3079. #else /* !WINDOWSNT */
  3080.       /* Now read; for one reason or another, this will not block.  */
  3081.       while (1)
  3082.     {
  3083.       nread = read (fileno (stdin), cbuf, nread);
  3084. #ifdef AIX
  3085.       /* The kernel sometimes fails to deliver SIGHUP for ptys.
  3086.          This looks incorrect, but it isn't, because _BSD causes
  3087.          O_NDELAY to be defined in fcntl.h as O_NONBLOCK,
  3088.          and that causes a value other than 0 when there is no input.  */
  3089.       if (nread == 0)
  3090.         kill (SIGHUP, 0);
  3091. #endif
  3092.       /* Retry the read if it is interrupted.  */
  3093.       if (nread >= 0
  3094.           || ! (errno == EAGAIN || errno == EFAULT
  3095. #ifdef EBADSLT
  3096.             || errno == EBADSLT
  3097. #endif
  3098.             ))
  3099.         break;
  3100.     }
  3101. #endif /* !WINDOWSNT */
  3102.  
  3103. #ifndef FIONREAD
  3104. #ifdef USG
  3105.       fcntl (fileno (stdin), F_SETFL, 0);
  3106. #endif /* USG */
  3107. #endif /* no FIONREAD */
  3108.       for (i = 0; i < nread; i++)
  3109.     {
  3110.       buf[i].kind = ascii_keystroke;
  3111.       buf[i].modifiers = 0;
  3112.       if (meta_key == 1 && (cbuf[i] & 0x80))
  3113.         buf[i].modifiers = meta_modifier;
  3114.       if (meta_key != 2)
  3115.         cbuf[i] &= ~0x80;
  3116.         
  3117.       XSET (buf[i].code,        Lisp_Int,   cbuf[i]);
  3118. #ifdef MULTI_FRAME
  3119.       XSET (buf[i].frame_or_window, Lisp_Frame, selected_frame);
  3120. #else
  3121.       buf[i].frame_or_window = Qnil;
  3122. #endif
  3123.     }
  3124.     }
  3125.  
  3126.   /* Scan the chars for C-g and store them in kbd_buffer.  */
  3127.   for (i = 0; i < nread; i++)
  3128.     {
  3129.       kbd_buffer_store_event (&buf[i]);
  3130.       /* Don't look at input that follows a C-g too closely.
  3131.      This reduces lossage due to autorepeat on C-g.  */
  3132.       if (buf[i].kind == ascii_keystroke
  3133.       && XINT(buf[i].code) == quit_char)
  3134.     break;
  3135.     }
  3136.  
  3137.   return nread;
  3138. }
  3139. #endif /* not VMS */
  3140.  
  3141. #ifdef SIGIO   /* for entire page */
  3142. /* Note SIGIO has been undef'd if FIONREAD is missing.  */
  3143.  
  3144. SIGTYPE
  3145. input_available_signal (signo)
  3146.      int signo;
  3147. {
  3148.   /* Must preserve main program's value of errno.  */
  3149.   int old_errno = errno;
  3150. #ifdef BSD4_1
  3151.   extern int select_alarmed;
  3152. #endif
  3153.  
  3154. #ifdef USG
  3155.   /* USG systems forget handlers when they are used;
  3156.      must reestablish each time */
  3157.   signal (signo, input_available_signal);
  3158. #endif /* USG */
  3159.  
  3160. #ifdef BSD4_1
  3161.   sigisheld (SIGIO);
  3162. #endif
  3163.  
  3164.   if (input_available_clear_time)
  3165.     EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
  3166.  
  3167.   while (1)
  3168.     {
  3169.       int nread;
  3170.       nread = read_avail_input (1);
  3171.       /* -1 means it's not ok to read the input now.
  3172.      UNBLOCK_INPUT will read it later; now, avoid infinite loop.
  3173.      0 means there was no keyboard input available.  */
  3174.       if (nread <= 0)
  3175.     break;
  3176.  
  3177. #ifdef BSD4_1
  3178.       select_alarmed = 1;  /* Force the select emulator back to life */
  3179. #endif
  3180.     }
  3181.  
  3182. #ifdef BSD4_1
  3183.   sigfree ();
  3184. #endif
  3185.   errno = old_errno;
  3186. }
  3187. #endif /* SIGIO */
  3188.  
  3189. /* Send ourselves a SIGIO.
  3190.  
  3191.    This function exists so that the UNBLOCK_INPUT macro in
  3192.    blockinput.h can have some way to take care of input we put off
  3193.    dealing with, without assuming that every file which uses
  3194.    UNBLOCK_INPUT also has #included the files necessary to get SIGIO. */
  3195. void
  3196. reinvoke_input_signal ()
  3197. {
  3198. #ifdef SIGIO  
  3199.   kill (0, SIGIO);
  3200. #endif
  3201. }
  3202.  
  3203.  
  3204.  
  3205. /* Return the prompt-string of a sparse keymap.
  3206.    This is the first element which is a string.
  3207.    Return nil if there is none.  */
  3208.  
  3209. Lisp_Object
  3210. map_prompt (map)
  3211.      Lisp_Object map;
  3212. {
  3213.   while (CONSP (map))
  3214.     {
  3215.       register Lisp_Object tem;
  3216.       tem = Fcar (map);
  3217.       if (XTYPE (tem) == Lisp_String)
  3218.     return tem;
  3219.       map = Fcdr (map);
  3220.     }
  3221.   return Qnil;
  3222. }
  3223.  
  3224. /* Return a list of menu items for a menu bar, appropriate
  3225.    to the current buffer.
  3226.    The elements have the form (KEY STRING . nil).  */
  3227.  
  3228. Lisp_Object
  3229. menu_bar_items ()
  3230. {
  3231.   /* The number of keymaps we're scanning right now, and the number of
  3232.      keymaps we have allocated space for.  */
  3233.   int nmaps;
  3234.  
  3235.   /* maps[0..nmaps-1] are the prefix definitions of KEYBUF[0..t-1]
  3236.      in the current keymaps, or nil where it is not a prefix.  */
  3237.   Lisp_Object *maps;
  3238.  
  3239.   Lisp_Object def, tem, tail;
  3240.  
  3241.   Lisp_Object result;
  3242.  
  3243.   int mapno;
  3244.   Lisp_Object oquit;
  3245.  
  3246.   /* In order to build the menus, we need to call the keymap
  3247.      accessors.  They all call QUIT.  But this function is called
  3248.      during redisplay, during which a quit is fatal.  So inhibit
  3249.      quitting while building the menus.
  3250.      We do this instead of specbind because (1) errors will clear it anyway
  3251.      and (2) this avoids risk of specpdl overflow.  */
  3252.   oquit = Vinhibit_quit;
  3253.   Vinhibit_quit = Qt; 
  3254.  
  3255.   /* Build our list of keymaps.
  3256.      If we recognize a function key and replace its escape sequence in
  3257.      keybuf with its symbol, or if the sequence starts with a mouse
  3258.      click and we need to switch buffers, we jump back here to rebuild
  3259.      the initial keymaps from the current buffer.  */
  3260.   { 
  3261.     Lisp_Object *tmaps;
  3262.  
  3263.     nmaps = current_minor_maps (0, &tmaps) + 2;
  3264.     maps = (Lisp_Object *) alloca (nmaps * sizeof (maps[0]));
  3265.     bcopy (tmaps, maps, (nmaps - 2) * sizeof (maps[0]));
  3266. #ifdef USE_TEXT_PROPERTIES
  3267.     maps[nmaps-2] = get_local_map (PT, current_buffer);
  3268. #else
  3269.     maps[nmaps-2] = current_buffer->keymap;
  3270. #endif
  3271.     maps[nmaps-1] = current_global_map;
  3272.   }
  3273.  
  3274.   /* Look up in each map the dummy prefix key `menu-bar'.  */
  3275.  
  3276.   result = Qnil;
  3277.  
  3278.   for (mapno = nmaps - 1; mapno >= 0; mapno--)
  3279.     {
  3280.       if (! NILP (maps[mapno]))
  3281.     def = get_keyelt (access_keymap (maps[mapno], Qmenu_bar, 1, 0));
  3282.       else
  3283.     def = Qnil;
  3284.  
  3285.       tem = Fkeymapp (def);
  3286.       if (!NILP (tem))
  3287.     result = menu_bar_one_keymap (def, result);
  3288.     }
  3289.  
  3290.   for (tail = Vmenu_bar_final_items; CONSP (tail); tail = XCONS (tail)->cdr)
  3291.     {
  3292.       Lisp_Object elt;
  3293.  
  3294.       elt = Fassq (XCONS (tail)->car, result);
  3295.       if (!NILP (elt))
  3296.     result = Fcons (elt, Fdelq (elt, result));
  3297.     }
  3298.  
  3299.   result = Fnreverse (result);
  3300.   Vinhibit_quit = oquit;
  3301.   return result;
  3302. }
  3303.  
  3304. /* Scan one map KEYMAP, accumulating any menu items it defines
  3305.    that have not yet been seen in RESULT.  Return the updated RESULT.  */
  3306.  
  3307. static Lisp_Object
  3308. menu_bar_one_keymap (keymap, result)
  3309.      Lisp_Object keymap, result;
  3310. {
  3311.   Lisp_Object tail, item, key, binding, item_string;
  3312.  
  3313.   /* Loop over all keymap entries that have menu strings.  */
  3314.   for (tail = keymap; XTYPE (tail) == Lisp_Cons; tail = XCONS (tail)->cdr)
  3315.     {
  3316.       item = XCONS (tail)->car;
  3317.       if (XTYPE (item) == Lisp_Cons)
  3318.     {
  3319.       key = XCONS (item)->car;
  3320.       binding = XCONS (item)->cdr;
  3321.       if (XTYPE (binding) == Lisp_Cons)
  3322.         {
  3323.           item_string = XCONS (binding)->car;
  3324.           if (XTYPE (item_string) == Lisp_String)
  3325.         result = menu_bar_item (key, item_string,
  3326.                     Fcdr (binding), result);
  3327.         }
  3328.       else if (EQ (binding, Qundefined))
  3329.         result = menu_bar_item (key, item_string,
  3330.                     binding, result);
  3331.     }
  3332.       else if (XTYPE (item) == Lisp_Vector)
  3333.     {
  3334.       /* Loop over the char values represented in the vector.  */
  3335.       int len = XVECTOR (item)->size;
  3336.       int c;
  3337.       for (c = 0; c < len; c++)
  3338.         {
  3339.           Lisp_Object character;
  3340.           XFASTINT (character) = c;
  3341.           binding = XVECTOR (item)->contents[c];
  3342.           if (XTYPE (binding) == Lisp_Cons)
  3343.         {
  3344.           item_string = XCONS (binding)->car;
  3345.           if (XTYPE (item_string) == Lisp_String)
  3346.             result = menu_bar_item (key, item_string,
  3347.                         Fcdr (binding), result);
  3348.         }
  3349.           else if (EQ (binding, Qundefined))
  3350.         result = menu_bar_item (key, item_string,
  3351.                     binding, result);
  3352.         }
  3353.     }
  3354.     }
  3355.  
  3356.   return result;
  3357. }
  3358.  
  3359. static Lisp_Object
  3360. menu_bar_item (key, item_string, def, result)
  3361.      Lisp_Object key, item_string, def, result;
  3362. {
  3363.   Lisp_Object tem;
  3364.   Lisp_Object enabled;
  3365.  
  3366.   if (EQ (def, Qundefined))
  3367.     {
  3368.       /* If a map has an explicit nil as definition,
  3369.      discard any previously made menu bar item.  */
  3370.       tem = Fassq (key, result);
  3371.       return Fdelq (tem, result);
  3372.     }
  3373.  
  3374.   /* See if this entry is enabled.  */
  3375.   enabled = Qt;
  3376.  
  3377.   if (XTYPE (def) == Lisp_Symbol)
  3378.     {
  3379.       /* No property, or nil, means enable.
  3380.      Otherwise, enable if value is not nil.  */
  3381.       tem = Fget (def, Qmenu_enable);
  3382.       if (!NILP (tem))
  3383.     enabled = Feval (tem);
  3384.     }
  3385.  
  3386.   /* Add an entry for this key and string
  3387.      if there is none yet.  */
  3388.   tem = Fassq (key, result);
  3389.   if (!NILP (enabled) && NILP (tem))
  3390.     result = Fcons (Fcons (key, Fcons (item_string, Qnil)), result);
  3391.  
  3392.   return result;
  3393. }
  3394.  
  3395. static int echo_flag;
  3396. static int echo_now;
  3397.  
  3398. /* Read a character using menus based on maps in the array MAPS.
  3399.    NMAPS is the length of MAPS.  Return nil if there are no menus in the maps.
  3400.    Return t if we displayed a menu but the user rejected it.
  3401.  
  3402.    PREV_EVENT is the previous input event, or nil if we are reading
  3403.    the first event of a key sequence.
  3404.  
  3405.    If USED_MOUSE_MENU is non-zero, then we set *USED_MOUSE_MENU to 1
  3406.    if we used a mouse menu to read the input, or zero otherwise.  If
  3407.    USED_MOUSE_MENU is zero, *USED_MOUSE_MENU is left alone.
  3408.  
  3409.    The prompting is done based on the prompt-string of the map
  3410.    and the strings associated with various map elements.  */
  3411.  
  3412. static Lisp_Object
  3413. read_char_menu_prompt (nmaps, maps, prev_event, used_mouse_menu)
  3414.      int nmaps;
  3415.      Lisp_Object *maps;
  3416.      Lisp_Object prev_event;
  3417.      int *used_mouse_menu;
  3418. {
  3419.   int mapno;
  3420.   register Lisp_Object name;
  3421.   int nlength;
  3422.   int width = FRAME_WIDTH (selected_frame) - 4;
  3423.   char *menu = (char *) alloca (width + 4);
  3424.   int idx = -1;
  3425.   Lisp_Object rest, vector;
  3426.  
  3427.   if (used_mouse_menu)
  3428.     *used_mouse_menu = 0;
  3429.  
  3430.   /* Use local over global Menu maps */
  3431.  
  3432.   if (! menu_prompting)
  3433.     return Qnil;
  3434.  
  3435.   /* Get the menu name from the first map that has one (a prompt string).  */
  3436.   for (mapno = 0; mapno < nmaps; mapno++)
  3437.     {
  3438.       name = map_prompt (maps[mapno]);
  3439.       if (!NILP (name))
  3440.     break;
  3441.     }
  3442.  
  3443.   /* If we don't have any menus, just read a character normally.  */
  3444.   if (mapno >= nmaps)
  3445.     return Qnil;
  3446.  
  3447. #ifdef HAVE_X_WINDOWS
  3448. #ifdef HAVE_X_MENU
  3449.   /* If we got to this point via a mouse click,
  3450.      use a real menu for mouse selection.  */
  3451.   if (EVENT_HAS_PARAMETERS (prev_event))
  3452.     {
  3453.       /* Display the menu and get the selection.  */
  3454.       Lisp_Object *realmaps
  3455.     = (Lisp_Object *) alloca (nmaps * sizeof (Lisp_Object));
  3456.       Lisp_Object value;
  3457.       int nmaps1 = 0;
  3458.  
  3459.       /* Use the maps that are not nil.  */
  3460.       for (mapno = 0; mapno < nmaps; mapno++)
  3461.     if (!NILP (maps[mapno]))
  3462.       realmaps[nmaps1++] = maps[mapno];
  3463.  
  3464.       value = Fx_popup_menu (prev_event, Flist (nmaps1, realmaps));
  3465.       if (CONSP (value))
  3466.     {
  3467.       /* If we got more than one event, put all but the first
  3468.          onto this list to be read later.
  3469.          Return just the first event now.  */
  3470.       unread_command_events
  3471.         = nconc2 (XCONS (value)->cdr, unread_command_events);
  3472.       value = XCONS (value)->car;
  3473.     }
  3474.       if (NILP (value))
  3475.     value = Qt;
  3476.       if (used_mouse_menu)
  3477.     *used_mouse_menu = 1;
  3478.       return value;
  3479.     }
  3480. #endif /* HAVE_X_MENU */
  3481. #endif /* HAVE_X_WINDOWS */
  3482.  
  3483.   /* Prompt string always starts with map's prompt, and a space.  */
  3484.   strcpy (menu, XSTRING (name)->data);
  3485.   nlength = XSTRING (name)->size;
  3486.   menu[nlength++] = ':';
  3487.   menu[nlength++] = ' ';
  3488.   menu[nlength] = 0;
  3489.  
  3490.   /* Start prompting at start of first map.  */
  3491.   mapno = 0;
  3492.   rest = maps[mapno];
  3493.  
  3494.   /* Present the documented bindings, a line at a time.  */
  3495.   while (1)
  3496.     {
  3497.       int notfirst = 0;
  3498.       int i = nlength;
  3499.       Lisp_Object obj;
  3500.       int ch;
  3501.  
  3502.       /* Loop over elements of map.  */
  3503.       while (i < width)
  3504.     {
  3505.       Lisp_Object s, elt;
  3506.  
  3507.       /* If reached end of map, start at beginning of next map.  */
  3508.       if (NILP (rest))
  3509.         {
  3510.           mapno++;
  3511.           /* At end of last map, wrap around to first map if just starting,
  3512.          or end this line if already have something on it.  */
  3513.           if (mapno == nmaps)
  3514.         {
  3515.           if (notfirst)
  3516.             break;
  3517.           else
  3518.             mapno = 0;
  3519.         }
  3520.           rest = maps[mapno];
  3521.         }
  3522.  
  3523.       /* Look at the next element of the map.  */
  3524.       if (idx >= 0)
  3525.         elt = XVECTOR (vector)->contents[idx];
  3526.       else
  3527.         elt = Fcar_safe (rest);
  3528.  
  3529.       if (idx < 0 && XTYPE (elt) == Lisp_Vector)
  3530.         {
  3531.           /* If we found a dense table in the keymap,
  3532.          advanced past it, but start scanning its contents.  */
  3533.           rest = Fcdr_safe (rest);
  3534.           vector = elt;
  3535.           idx = 0;
  3536.         }
  3537.       else
  3538.         {
  3539.           /* An ordinary element.  */
  3540.           s = Fcar_safe (Fcdr_safe (elt));
  3541.           if (XTYPE (s) != Lisp_String)
  3542.         /* Ignore the element if it has no prompt string.  */
  3543.         ;
  3544.           /* If we have room for the prompt string, add it to this line.
  3545.          If this is the first on the line, always add it.  */
  3546.           else if (XSTRING (s)->size + i < width
  3547.                || !notfirst)
  3548.         {
  3549.           int thiswidth;
  3550.  
  3551.           /* Punctuate between strings.  */
  3552.           if (notfirst)
  3553.             {
  3554.               strcpy (menu + i, ", ");
  3555.               i += 2;
  3556.             }
  3557.           notfirst = 1;
  3558.  
  3559.           /* Add as much of string as fits.  */
  3560.           thiswidth = XSTRING (s)->size;
  3561.           if (thiswidth + i > width)
  3562.             thiswidth = width - i;
  3563.           bcopy (XSTRING (s)->data, menu + i, thiswidth);
  3564.           i += thiswidth;
  3565.         }
  3566.           else
  3567.         {
  3568.           /* If this element does not fit, end the line now,
  3569.              and save the element for the next line.  */
  3570.           strcpy (menu + i, "...");
  3571.           break;
  3572.         }
  3573.  
  3574.           /* Move past this element.  */
  3575.           if (idx >= 0 && idx + 1 >= XVECTOR (rest)->size)
  3576.         /* Handle reaching end of dense table.  */
  3577.         idx = -1;
  3578.           if (idx >= 0)
  3579.         idx++;
  3580.           else
  3581.         rest = Fcdr_safe (rest);
  3582.         }
  3583.     }
  3584.  
  3585.       /* Prompt with that and read response.  */
  3586.       message1 (menu);
  3587.       obj = read_char (1, 0, 0, Qnil, 0);
  3588.  
  3589.       if (XTYPE (obj) != Lisp_Int)
  3590.     return obj;
  3591.       else
  3592.     ch = XINT (obj);
  3593.  
  3594.       if (! EQ (obj, menu_prompt_more_char)
  3595.       && (XTYPE (menu_prompt_more_char) != Lisp_Int
  3596.           || ! EQ (obj, make_number (Ctl (XINT (menu_prompt_more_char))))))
  3597.     return obj;
  3598.     }
  3599. }
  3600.  
  3601. /* Reading key sequences.  */
  3602.  
  3603. /* Follow KEY in the maps in CURRENT[0..NMAPS-1], placing its bindings
  3604.    in DEFS[0..NMAPS-1].  Set NEXT[i] to DEFS[i] if DEFS[i] is a
  3605.    keymap, or nil otherwise.  Return the index of the first keymap in
  3606.    which KEY has any binding, or NMAPS if no map has a binding.
  3607.  
  3608.    If KEY is a meta ASCII character, treat it like meta-prefix-char
  3609.    followed by the corresponding non-meta character.  Keymaps in
  3610.    CURRENT with non-prefix bindings for meta-prefix-char become nil in
  3611.    NEXT.
  3612.  
  3613.    When KEY is not defined in any of the keymaps, if it is an upper
  3614.    case letter and there are bindings for the corresponding lower-case
  3615.    letter, return the bindings for the lower-case letter.
  3616.  
  3617.    If KEY has no bindings in any of the CURRENT maps, NEXT is left
  3618.    unmodified.
  3619.  
  3620.    NEXT may == CURRENT.  */
  3621.  
  3622. static int
  3623. follow_key (key, nmaps, current, defs, next)
  3624.      Lisp_Object key;
  3625.      Lisp_Object *current, *defs, *next;
  3626.      int nmaps;
  3627. {
  3628.   int i, first_binding;
  3629.  
  3630.   /* If KEY is a meta ASCII character, treat it like meta-prefix-char
  3631.      followed by the corresponding non-meta character.  */
  3632.   if (XTYPE (key) == Lisp_Int && (XINT (key) & CHAR_META))
  3633.     {
  3634.       for (i = 0; i < nmaps; i++)
  3635.     if (! NILP (current[i]))
  3636.       {
  3637.         next[i] =
  3638.           get_keyelt (access_keymap (current[i], meta_prefix_char, 1, 0));
  3639.  
  3640.         /* Note that since we pass the resulting bindings through
  3641.            get_keymap_1, non-prefix bindings for meta-prefix-char
  3642.            disappear.  */
  3643.         next[i] = get_keymap_1 (next[i], 0, 1);
  3644.       }
  3645.     else
  3646.       next[i] = Qnil;
  3647.  
  3648.       current = next;
  3649.       XSET (key, Lisp_Int, XFASTINT (key) & ~CHAR_META);
  3650.     }
  3651.  
  3652.   first_binding = nmaps;
  3653.   for (i = nmaps - 1; i >= 0; i--)
  3654.     {
  3655.       if (! NILP (current[i]))
  3656.     {
  3657.       defs[i] = get_keyelt (access_keymap (current[i], key, 1, 0));
  3658.       if (! NILP (defs[i]))
  3659.         first_binding = i;
  3660.     }
  3661.       else
  3662.     defs[i] = Qnil;
  3663.     }
  3664.  
  3665.   /* When KEY is not defined in any of the keymaps, if it is an upper
  3666.      case letter and there are bindings for the corresponding
  3667.      lower-case letter, return the bindings for the lower-case letter.  */
  3668.   if (first_binding == nmaps
  3669.       && XTYPE (key) == Lisp_Int
  3670.       && ((((XINT (key) & 0x3ffff)
  3671.         < XSTRING (current_buffer->downcase_table)->size)
  3672.        && UPPERCASEP (XINT (key) & 0x3ffff))
  3673.       || (XINT (key) & shift_modifier)))
  3674.     {
  3675.       if (XINT (key) & shift_modifier)
  3676.     XSETINT (key, XINT (key) & ~shift_modifier);
  3677.       else
  3678.     XSETINT (key, DOWNCASE (XINT (key)));
  3679.  
  3680.       first_binding = nmaps;
  3681.       for (i = nmaps - 1; i >= 0; i--)
  3682.     {
  3683.       if (! NILP (current[i]))
  3684.         {
  3685.           defs[i] = get_keyelt (access_keymap (current[i], key, 1, 0));
  3686.           if (! NILP (defs[i]))
  3687.         first_binding = i;
  3688.         }
  3689.       else
  3690.         defs[i] = Qnil;
  3691.     }
  3692.     }
  3693.  
  3694.   /* Given the set of bindings we've found, produce the next set of maps.  */
  3695.   if (first_binding < nmaps)
  3696.     for (i = 0; i < nmaps; i++)
  3697.       next[i] = NILP (defs[i]) ? Qnil : get_keymap_1 (defs[i], 0, 1);
  3698.  
  3699.   return first_binding;
  3700. }
  3701.  
  3702. /* Read a sequence of keys that ends with a non prefix character, 
  3703.    storing it in KEYBUF, a buffer of size BUFSIZE.
  3704.    Prompt with PROMPT.
  3705.    Return the length of the key sequence stored.
  3706.    Return -1 if the user rejected a command menu.
  3707.  
  3708.    Echo starting immediately unless `prompt' is 0.
  3709.  
  3710.    Where a key sequence ends depends on the currently active keymaps.
  3711.    These include any minor mode keymaps active in the current buffer,
  3712.    the current buffer's local map, and the global map.
  3713.  
  3714.    If a key sequence has no other bindings, we check Vfunction_key_map
  3715.    to see if some trailing subsequence might be the beginning of a
  3716.    function key's sequence.  If so, we try to read the whole function
  3717.    key, and substitute its symbolic name into the key sequence.
  3718.  
  3719.    We ignore unbound `down-' mouse clicks.  We turn unbound `drag-' and
  3720.    `double-' events into similar click events, if that would make them
  3721.    bound.  We try to turn `triple-' events first into `double-' events,
  3722.    then into clicks.
  3723.  
  3724.    If we get a mouse click in a mode line, vertical divider, or other
  3725.    non-text area, we treat the click as if it were prefixed by the
  3726.    symbol denoting that area - `mode-line', `vertical-line', or
  3727.    whatever.
  3728.  
  3729.    If the sequence starts with a mouse click, we read the key sequence
  3730.    with respect to the buffer clicked on, not the current buffer.
  3731.  
  3732.    If the user switches frames in the midst of a key sequence, we put
  3733.    off the switch-frame event until later; the next call to
  3734.    read_char will return it.  */
  3735.  
  3736. static int
  3737. read_key_sequence (keybuf, bufsize, prompt)
  3738.      Lisp_Object *keybuf;
  3739.      int bufsize;
  3740.      char *prompt;
  3741. {
  3742.   int count = specpdl_ptr - specpdl;
  3743.  
  3744.   /* How many keys there are in the current key sequence.  */
  3745.   int t;
  3746.  
  3747.   /* The length of the echo buffer when we started reading, and
  3748.      the length of this_command_keys when we started reading.  */
  3749.   int echo_start;
  3750.   int keys_start;
  3751.  
  3752.   /* The number of keymaps we're scanning right now, and the number of
  3753.      keymaps we have allocated space for.  */
  3754.   int nmaps;
  3755.   int nmaps_allocated = 0;
  3756.  
  3757.   /* defs[0..nmaps-1] are the definitions of KEYBUF[0..t-1] in
  3758.      the current keymaps.  */
  3759.   Lisp_Object *defs;
  3760.  
  3761.   /* submaps[0..nmaps-1] are the prefix definitions of KEYBUF[0..t-1]
  3762.      in the current keymaps, or nil where it is not a prefix.  */
  3763.   Lisp_Object *submaps;
  3764.  
  3765.   /* The index in defs[] of the first keymap that has a binding for
  3766.      this key sequence.  In other words, the lowest i such that
  3767.      defs[i] is non-nil.  */
  3768.   int first_binding;
  3769.  
  3770.   /* If t < mock_input, then KEYBUF[t] should be read as the next
  3771.      input key.
  3772.  
  3773.      We use this to recover after recognizing a function key.  Once we
  3774.      realize that a suffix of the current key sequence is actually a
  3775.      function key's escape sequence, we replace the suffix with the
  3776.      function key's binding from Vfunction_key_map.  Now keybuf
  3777.      contains a new and different key sequence, so the echo area,
  3778.      this_command_keys, and the submaps and defs arrays are wrong.  In
  3779.      this situation, we set mock_input to t, set t to 0, and jump to
  3780.      restart_sequence; the loop will read keys from keybuf up until
  3781.      mock_input, thus rebuilding the state; and then it will resume
  3782.      reading characters from the keyboard.  */
  3783.   int mock_input = 0;
  3784.  
  3785.   /* If the sequence is unbound in submaps[], then
  3786.      keybuf[fkey_start..fkey_end-1] is a prefix in Vfunction_key_map,
  3787.      and fkey_map is its binding.
  3788.  
  3789.      These might be > t, indicating that all function key scanning
  3790.      should hold off until t reaches them.  We do this when we've just
  3791.      recognized a function key, to avoid searching for the function
  3792.      key's again in Vfunction_key_map.  */
  3793.   int fkey_start = 0, fkey_end = 0;
  3794.   Lisp_Object fkey_map;
  3795.  
  3796.   /* If we receive a ``switch-frame'' event in the middle of a key sequence,
  3797.      we put it off for later.  While we're reading, we keep the event here.  */
  3798.   Lisp_Object delayed_switch_frame;
  3799.  
  3800. #if 0
  3801.   Lisp_Object first_event;
  3802.   int junk;
  3803. #endif
  3804.  
  3805. #ifdef WINDOWSNT
  3806.   int dummyFlag = 0;
  3807. #endif
  3808.  
  3809.   last_nonmenu_event = Qnil;
  3810.  
  3811.   delayed_switch_frame = Qnil;
  3812.   fkey_map = Vfunction_key_map;
  3813.  
  3814.   /* If there is no function key map, turn off function key scanning.  */
  3815.   if (NILP (Fkeymapp (Vfunction_key_map)))
  3816.     fkey_start = fkey_end = bufsize + 1;
  3817.  
  3818.   if (INTERACTIVE)
  3819.     {
  3820.       if (prompt)
  3821.     echo_prompt (prompt);
  3822.       else if (cursor_in_echo_area)
  3823.     /* This doesn't put in a dash if the echo buffer is empty, so
  3824.        you don't always see a dash hanging out in the minibuffer.  */
  3825.     echo_dash ();
  3826.     }
  3827.  
  3828.   /* Record the initial state of the echo area and this_command_keys;
  3829.      we will need to restore them if we replay a key sequence.  */
  3830.   if (INTERACTIVE)
  3831.     echo_start = echo_length ();
  3832.   keys_start = this_command_key_count;
  3833.  
  3834. #if 0 /* This doesn't quite work, because some of the things
  3835.      that read_char does cannot safely be bypassed.
  3836.      It seems too risky to try to make this work right.  */ 
  3837.   /* Read the first char of the sequence specially, before setting
  3838.      up any keymaps, in case a filter runs and switches buffers on us.  */
  3839.   first_event = read_char (!prompt, 0, submaps, last_nonmenu_event,
  3840.                &junk);
  3841. #endif
  3842.  
  3843.   /* We jump here when the key sequence has been thoroughly changed, and
  3844.      we need to rescan it starting from the beginning.  When we jump here,
  3845.      keybuf[0..mock_input] holds the sequence we should reread.  */
  3846.  replay_sequence:
  3847.  
  3848.   /* Build our list of keymaps.
  3849.      If we recognize a function key and replace its escape sequence in
  3850.      keybuf with its symbol, or if the sequence starts with a mouse
  3851.      click and we need to switch buffers, we jump back here to rebuild
  3852.      the initial keymaps from the current buffer.  */
  3853.   { 
  3854.     Lisp_Object *maps;
  3855.  
  3856.     nmaps = current_minor_maps (0, &maps) + 2;
  3857.     if (nmaps > nmaps_allocated)
  3858.       {
  3859.     submaps = (Lisp_Object *) alloca (nmaps * sizeof (submaps[0]));
  3860.     defs    = (Lisp_Object *) alloca (nmaps * sizeof (defs[0]));
  3861.     nmaps_allocated = nmaps;
  3862.       }
  3863.     bcopy (maps, submaps, (nmaps - 2) * sizeof (submaps[0]));
  3864. #ifdef USE_TEXT_PROPERTIES
  3865.     submaps[nmaps-2] = get_local_map (PT, current_buffer);
  3866. #else
  3867.     submaps[nmaps-2] = current_buffer->keymap;
  3868. #endif
  3869.     submaps[nmaps-1] = current_global_map;
  3870.   }
  3871.  
  3872.   /* Find an accurate initial value for first_binding.  */
  3873.   for (first_binding = 0; first_binding < nmaps; first_binding++)
  3874.     if (! NILP (submaps[first_binding]))
  3875.       break;
  3876.  
  3877.   /* We jump here when a function key substitution has forced us to
  3878.      reprocess the current key sequence.  keybuf[0..mock_input] is the
  3879.      sequence we want to reread.  */
  3880.   t = 0;
  3881.  
  3882.   /* These are no-ops the first time through, but if we restart, they
  3883.      revert the echo area and this_command_keys to their original state.  */
  3884.   this_command_key_count = keys_start;
  3885.   if (INTERACTIVE)
  3886.     echo_truncate (echo_start);
  3887.  
  3888.   /* If the best binding for the current key sequence is a keymap, or
  3889.      we may be looking at a function key's escape sequence, keep on
  3890.      reading.  */
  3891.   while ((first_binding < nmaps && ! NILP (submaps[first_binding]))
  3892.      || (first_binding >= nmaps
  3893.          && fkey_start < t
  3894.          /* mock input is never part of a function key's sequence.  */
  3895.          && mock_input <= fkey_start))
  3896.     {
  3897.       Lisp_Object key;
  3898.       int used_mouse_menu = 0;
  3899.  
  3900.       /* Where the last real key started.  If we need to throw away a
  3901.          key that has expanded into more than one element of keybuf
  3902.          (say, a mouse click on the mode line which is being treated
  3903.          as [mode-line (mouse-...)], then we backtrack to this point
  3904.          of keybuf.  */
  3905.       int last_real_key_start;
  3906.  
  3907.       /* These variables are analogous to echo_start and keys_start;
  3908.      while those allow us to restart the entire key sequence,
  3909.      echo_local_start and keys_local_start allow us to throw away
  3910.      just one key.  */
  3911.       int echo_local_start, keys_local_start, local_first_binding;
  3912.  
  3913.       if (t >= bufsize)
  3914.     error ("key sequence too long");
  3915.  
  3916.       if (INTERACTIVE)
  3917.     echo_local_start = echo_length ();
  3918.       keys_local_start = this_command_key_count;
  3919.       local_first_binding = first_binding;
  3920.       
  3921.     replay_key:
  3922.       /* These are no-ops, unless we throw away a keystroke below and
  3923.      jumped back up to replay_key; in that case, these restore the
  3924.      variables to their original state, allowing us to replay the
  3925.      loop.  */
  3926.       if (INTERACTIVE)
  3927.     echo_truncate (echo_local_start);
  3928.       this_command_key_count = keys_local_start;
  3929.       first_binding = local_first_binding;
  3930.  
  3931.       /* By default, assume each event is "real".  */
  3932.       last_real_key_start = t;
  3933.  
  3934.       /* Does mock_input indicate that we are re-reading a key sequence?  */
  3935.       if (t < mock_input)
  3936.     {
  3937.       key = keybuf[t];
  3938.       add_command_key (key);
  3939.       echo_char (key);
  3940.     }
  3941.  
  3942.       /* If not, we should actually read a character.  */
  3943.       else
  3944.     {
  3945.       struct buffer *buf = current_buffer;
  3946.  
  3947.       key = read_char (!prompt, nmaps, submaps, last_nonmenu_event,
  3948.                &used_mouse_menu);
  3949.  
  3950.       /* read_char returns t when it shows a menu and the user rejects it.
  3951.          Just return -1.  */
  3952.       if (EQ (key, Qt))
  3953.         return -1;
  3954.  
  3955.       /* read_char returns -1 at the end of a macro.
  3956.          Emacs 18 handles this by returning immediately with a
  3957.          zero, so that's what we'll do.  */
  3958.       if (XTYPE (key) == Lisp_Int && XINT (key) == -1)
  3959.         {
  3960.           t = 0;
  3961. #ifdef WINDOWSNT
  3962.           /*
  3963.            * The Microsoft C compiler can't handle these gotos.
  3964.            */
  3965.           if (1) {
  3966.           dummyFlag = 1;
  3967.           break;
  3968.           }
  3969.  
  3970. #else  /* !WINDOWS NT */
  3971.           goto done;
  3972. #endif /* !WINDOWS NT */
  3973.         }
  3974.       
  3975.       Vquit_flag = Qnil;
  3976.     }
  3977.  
  3978.       /* Clicks in non-text areas get prefixed by the symbol 
  3979.      in their CHAR-ADDRESS field.  For example, a click on
  3980.      the mode line is prefixed by the symbol `mode-line'.
  3981.  
  3982.      Furthermore, key sequences beginning with mouse clicks
  3983.      are read using the keymaps of the buffer clicked on, not
  3984.      the current buffer.  So we may have to switch the buffer
  3985.      here.
  3986.  
  3987.      When we turn one event into two events, we must make sure
  3988.      that neither of the two looks like the original--so that,
  3989.      if we replay the events, they won't be expanded again.
  3990.      If not for this, such reexpansion could happen either here
  3991.      or when user programs play with this-command-keys.  */
  3992.       if (EVENT_HAS_PARAMETERS (key))
  3993.     {
  3994.       Lisp_Object kind = EVENT_HEAD_KIND (EVENT_HEAD (key));
  3995.  
  3996.       if (EQ (kind, Qmouse_click))
  3997.         {
  3998.           Lisp_Object window = POSN_WINDOW      (EVENT_START (key));
  3999.           Lisp_Object posn   = POSN_BUFFER_POSN (EVENT_START (key));
  4000.  
  4001.           if (XTYPE (posn) == Lisp_Cons)
  4002.         {
  4003.           /* We're looking at the second event of a
  4004.              sequence which we expanded before.  Set
  4005.              last_real_key_start appropriately.  */
  4006.           if (t > 0)
  4007.             last_real_key_start = t - 1;
  4008.         }
  4009.  
  4010.           /* Key sequences beginning with mouse clicks are
  4011.          read using the keymaps in the buffer clicked on,
  4012.          not the current buffer.  If we're at the
  4013.          beginning of a key sequence, switch buffers.  */
  4014.           if (last_real_key_start == 0
  4015.           && XTYPE (window) == Lisp_Window
  4016.           && XTYPE (XWINDOW (window)->buffer) == Lisp_Buffer
  4017.           && XBUFFER (XWINDOW (window)->buffer) != current_buffer)
  4018.         {
  4019.           keybuf[t] = key;
  4020.           mock_input = t + 1;
  4021.  
  4022.           /* Arrange to go back to the original buffer once we're
  4023.              done reading the key sequence.  Note that we can't
  4024.              use save_excursion_{save,restore} here, because they
  4025.              save point as well as the current buffer; we don't
  4026.              want to save point, because redisplay may change it,
  4027.              to accommodate a Fset_window_start or something.  We
  4028.              don't want to do this at the top of the function,
  4029.              because we may get input from a subprocess which
  4030.              wants to change the selected window and stuff (say,
  4031.              emacsclient).  */
  4032.           record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
  4033.  
  4034.           set_buffer_internal (XBUFFER (XWINDOW (window)->buffer));
  4035.           goto replay_sequence;
  4036.         }
  4037.           else if (XTYPE (posn) == Lisp_Symbol)
  4038.         {
  4039.           /* Expand mode-line and scroll-bar events into two events:
  4040.              use posn as a fake prefix key.  */
  4041.  
  4042.           if (t + 1 >= bufsize)
  4043.             error ("key sequence too long");
  4044.           keybuf[t] = posn;
  4045.           keybuf[t+1] = key;
  4046.           mock_input = t + 2;
  4047.  
  4048.           /* Zap the position in key, so we know that we've
  4049.              expanded it, and don't try to do so again.  */
  4050.           POSN_BUFFER_POSN (EVENT_START (key))
  4051.             = Fcons (posn, Qnil);
  4052.           goto replay_key;
  4053.         }
  4054.         }
  4055.       else if (EQ (kind, Qswitch_frame))
  4056.         {
  4057.           /* If we're at the beginning of a key sequence, go
  4058.          ahead and return this event.  If we're in the
  4059.          midst of a key sequence, delay it until the end. */
  4060.           if (t > 0)
  4061.         {
  4062.           delayed_switch_frame = key;
  4063.           goto replay_key;
  4064.         }
  4065.         }
  4066.       else
  4067.         {
  4068.           Lisp_Object posn   = POSN_BUFFER_POSN (EVENT_START (key));
  4069.  
  4070.           /* Handle menu-bar events:
  4071.          insert the dummy prefix event `menu-bar'.  */
  4072.           if (EQ (posn, Qmenu_bar))
  4073.         {
  4074.           if (t + 1 >= bufsize)
  4075.             error ("key sequence too long");
  4076.           /* Run the Lucid hook.  */
  4077.           call1 (Vrun_hooks, Qactivate_menubar_hook);
  4078.           /* If it has changed current-menubar from previous value,
  4079.              really recompute the menubar from the value.  */
  4080.           if (! NILP (Vlucid_menu_bar_dirty_flag))
  4081.             call0 (Qrecompute_lucid_menubar);
  4082.           keybuf[t] = posn;
  4083.           keybuf[t+1] = key;
  4084.  
  4085.           /* Zap the position in key, so we know that we've
  4086.              expanded it, and don't try to do so again.  */
  4087.           POSN_BUFFER_POSN (EVENT_START (key))
  4088.             = Fcons (posn, Qnil);
  4089.  
  4090.           mock_input = t + 2;
  4091.           goto replay_sequence;
  4092.         }
  4093.           else if (XTYPE (posn) == Lisp_Cons)
  4094.         {
  4095.           /* We're looking at the second event of a
  4096.              sequence which we expanded before.  Set
  4097.              last_real_key_start appropriately.  */
  4098.           if (last_real_key_start == t && t > 0)
  4099.             last_real_key_start = t - 1;
  4100.         }
  4101.         }
  4102.     }
  4103.  
  4104.       /* We have finally decided that KEY is something we might want
  4105.      to look up.  */
  4106.       first_binding = (follow_key (key,
  4107.                    nmaps   - first_binding,
  4108.                    submaps + first_binding,
  4109.                    defs    + first_binding,
  4110.                    submaps + first_binding)
  4111.                + first_binding);
  4112.  
  4113.       /* If KEY wasn't bound, we'll try some fallbacks.  */
  4114.       if (first_binding >= nmaps)
  4115.     {
  4116.       Lisp_Object head = EVENT_HEAD (key);
  4117.  
  4118.       if (EQ (head, Vhelp_char))
  4119.         {
  4120.           read_key_sequence_cmd = Vprefix_help_command;
  4121.           keybuf[t++] = key;
  4122.           last_nonmenu_event = key;
  4123. #ifdef WINDOWSNT
  4124.           /*
  4125.            * The Microsoft C compiler can't handle these gotos.
  4126.            */
  4127.           if (1) {
  4128.           dummyFlag = 1;
  4129. /*          break; */
  4130.           }
  4131.  
  4132. #else  /* !WINDOWS NT */
  4133.           goto done;
  4134. #endif /* !WINDOWS NT */
  4135.         }
  4136.  
  4137.       if (dummyFlag) {
  4138.           break;
  4139.       }
  4140.  
  4141.       if (XTYPE (head) == Lisp_Symbol)
  4142.         {
  4143.           Lisp_Object breakdown = parse_modifiers (head);
  4144.           int modifiers = XINT (XCONS (XCONS (breakdown)->cdr)->car);
  4145.  
  4146.           /* We drop unbound `down-' events altogether.  */
  4147.           if (modifiers & down_modifier)
  4148.         {
  4149.           /* Dispose of this event by simply jumping back to
  4150.              replay_key, to get another event.
  4151.  
  4152.              Note that if this event came from mock input,
  4153.              then just jumping back to replay_key will just
  4154.              hand it to us again.  So we have to wipe out any
  4155.              mock input.
  4156.  
  4157.              We could delete keybuf[t] and shift everything
  4158.              after that to the left by one spot, but we'd also
  4159.              have to fix up any variable that points into
  4160.              keybuf, and shifting isn't really necessary
  4161.              anyway.
  4162.  
  4163.              Adding prefixes for non-textual mouse clicks
  4164.              creates two characters of mock input, and both
  4165.              must be thrown away.  If we're only looking at
  4166.              the prefix now, we can just jump back to
  4167.              replay_key.  On the other hand, if we've already
  4168.              processed the prefix, and now the actual click
  4169.              itself is giving us trouble, then we've lost the
  4170.              state of the keymaps we want to backtrack to, and
  4171.              we need to replay the whole sequence to rebuild
  4172.              it.
  4173.  
  4174.              Beyond that, only function key expansion could
  4175.              create more than two keys, but that should never
  4176.              generate mouse events, so it's okay to zero
  4177.              mock_input in that case too.
  4178.  
  4179.              Isn't this just the most wonderful code ever?  */
  4180.           if (t == last_real_key_start)
  4181.             {
  4182.               mock_input = 0;
  4183.               goto replay_key;
  4184.             }
  4185.           else
  4186.             {
  4187.               mock_input = last_real_key_start;
  4188.               goto replay_sequence;
  4189.             }
  4190.         }
  4191.  
  4192.           /* We turn unbound `drag-' events into `click-'
  4193.          events, if the click would be bound.  */
  4194.           else if (modifiers & (drag_modifier | double_modifier
  4195.                     | triple_modifier))
  4196.         {
  4197.           while (modifiers & (drag_modifier | double_modifier
  4198.                       | triple_modifier))
  4199.             {
  4200.               Lisp_Object new_head, new_click;
  4201.               if (modifiers & triple_modifier)
  4202.             modifiers ^= (double_modifier | triple_modifier);
  4203.               else
  4204.             modifiers &= ~(drag_modifier | double_modifier);
  4205.               new_head =
  4206.             apply_modifiers (modifiers, XCONS (breakdown)->car);
  4207.               new_click =
  4208.             Fcons (new_head, Fcons (EVENT_START (key), Qnil));
  4209.  
  4210.               /* Look for a binding for this new key.  follow_key
  4211.              promises that it didn't munge submaps the
  4212.              last time we called it, since key was unbound.  */
  4213.               first_binding =
  4214.             (follow_key (new_click,
  4215.                      nmaps   - local_first_binding,
  4216.                      submaps + local_first_binding,
  4217.                      defs    + local_first_binding,
  4218.                      submaps + local_first_binding)
  4219.              + local_first_binding);
  4220.  
  4221.               /* If that click is bound, go for it.  */
  4222.               if (first_binding < nmaps)
  4223.             {
  4224.               key = new_click;
  4225.               break;
  4226.             }
  4227.               /* Otherwise, we'll leave key set to the drag event.  */
  4228.             }
  4229.         }
  4230.         }
  4231.     }
  4232.  
  4233.       keybuf[t++] = key;
  4234.       /* Normally, last_nonmenu_event gets the previous key we read.
  4235.      But when a mouse popup menu is being used,
  4236.      we don't update last_nonmenu_event; it continues to hold the mouse
  4237.      event that preceded the first level of menu.  */
  4238.       if (!used_mouse_menu)
  4239.     last_nonmenu_event = key;
  4240.  
  4241.       /* If the sequence is unbound, see if we can hang a function key
  4242.      off the end of it.  We only want to scan real keyboard input
  4243.      for function key sequences, so if mock_input says that we're
  4244.      re-reading old events, don't examine it.  */
  4245.       if (first_binding >= nmaps
  4246.       && t >= mock_input)
  4247.     {
  4248.       Lisp_Object fkey_next;
  4249.  
  4250.       /* Scan from fkey_end until we find a bound suffix.  */
  4251.       while (fkey_end < t)
  4252.         {
  4253.           Lisp_Object key;
  4254.  
  4255.           key = keybuf[fkey_end++];
  4256.           /* Look up meta-characters by prefixing them
  4257.          with meta_prefix_char.  I hate this.  */
  4258.           if (XTYPE (key) == Lisp_Int && XINT (key) & meta_modifier)
  4259.         {
  4260.           fkey_next
  4261.             = get_keymap_1
  4262.               (get_keyelt
  4263.                (access_keymap (fkey_map, meta_prefix_char, 1, 0)),
  4264.                0, 1);
  4265.           XFASTINT (key) = XFASTINT (key) & ~meta_modifier;
  4266.         }
  4267.           else
  4268.         fkey_next = fkey_map;
  4269.  
  4270.           fkey_next
  4271.         = get_keyelt (access_keymap (fkey_next, key, 1, 0));
  4272.  
  4273.           /* If keybuf[fkey_start..fkey_end] is bound in the
  4274.          function key map and it's a suffix of the current
  4275.          sequence (i.e. fkey_end == t), replace it with
  4276.          the binding and restart with fkey_start at the end. */
  4277.           if ((VECTORP (fkey_next) || STRINGP (fkey_next))
  4278.           && fkey_end == t)
  4279.         {
  4280.           int len = Flength (fkey_next);
  4281.  
  4282.           t = fkey_start + len;
  4283.           if (t >= bufsize)
  4284.             error ("key sequence too long");
  4285.  
  4286.           if (VECTORP (fkey_next))
  4287.             bcopy (XVECTOR (fkey_next)->contents,
  4288.                keybuf + fkey_start,
  4289.                (t - fkey_start) * sizeof (keybuf[0]));
  4290.           else if (STRINGP (fkey_next))
  4291.             {
  4292.               int i;
  4293.  
  4294.               for (i = 0; i < len; i++)
  4295.             XFASTINT (keybuf[fkey_start + i]) =
  4296.               XSTRING (fkey_next)->data[i];
  4297.             }
  4298.           
  4299.           mock_input = t;
  4300.           fkey_start = fkey_end = t;
  4301.           fkey_map = Vfunction_key_map;
  4302.  
  4303.           goto replay_sequence;
  4304.         }
  4305.           
  4306.           fkey_map = get_keymap_1 (fkey_next, 0, 1);
  4307.  
  4308.           /* If we no longer have a bound suffix, try a new positions for 
  4309.          fkey_start.  */
  4310.           if (NILP (fkey_map))
  4311.         {
  4312.           fkey_end = ++fkey_start;
  4313.           fkey_map = Vfunction_key_map;
  4314.         }
  4315.         }
  4316.     }
  4317.     }
  4318.  
  4319. #ifdef WINDOWSNT
  4320.   if (!dummyFlag) {
  4321.       read_key_sequence_cmd = (first_binding < nmaps
  4322.                    ? defs[first_binding]
  4323.                    : Qnil);
  4324.   }
  4325. #else
  4326.  
  4327.   read_key_sequence_cmd = (first_binding < nmaps
  4328.                ? defs[first_binding]
  4329.                : Qnil);
  4330. #endif
  4331.  
  4332. #ifndef WINDOWSNT
  4333. done:
  4334. #endif /* !WINDOWSNT */
  4335.  
  4336.   unread_switch_frame = delayed_switch_frame;
  4337.   unbind_to (count, Qnil);
  4338.  
  4339.   /* Occasionally we fabricate events, perhaps by expanding something
  4340.      according to function-key-map, or by adding a prefix symbol to a
  4341.      mouse click in the scroll bar or modeline.  In this cases, return
  4342.      the entire generated key sequence, even if we hit an unbound
  4343.      prefix or a definition before the end.  This means that you will
  4344.      be able to push back the event properly, and also means that
  4345.      read-key-sequence will always return a logical unit.
  4346.  
  4347.      Better ideas?  */
  4348.   for (; t < mock_input; t++)
  4349.     {
  4350.       echo_char (keybuf[t]);
  4351.       add_command_key (keybuf[t]);
  4352.     }
  4353.  
  4354.   return t;
  4355. }
  4356.  
  4357. DEFUN ("read-key-sequence", Fread_key_sequence, Sread_key_sequence, 1, 2, 0,
  4358.   "Read a sequence of keystrokes and return as a string or vector.\n\
  4359. The sequence is sufficient to specify a non-prefix command in the\n\
  4360. current local and global maps.\n\
  4361. \n\
  4362. First arg PROMPT is a prompt string.  If nil, do not prompt specially.\n\
  4363. Second (optional) arg CONTINUE-ECHO, if non-nil, means this key echos\n\
  4364. as a continuation of the previous key.\n\
  4365. \n\
  4366. A C-g typed while in this function is treated like any other character,\n\
  4367. and `quit-flag' is not set.\n\
  4368. \n\
  4369. If the key sequence starts with a mouse click, then the sequence is read\n\
  4370. using the keymaps of the buffer of the window clicked in, not the buffer\n\
  4371. of the selected window as normal.\n\
  4372. \n\
  4373. `read-key-sequence' drops unbound button-down events, since you normally\n\
  4374. only care about the click or drag events which follow them.  If a drag\n\
  4375. or multi-click event is unbound, but the corresponding click event would\n\
  4376. be bound, `read-key-sequence' turns the event into a click event at the\n\
  4377. drag's starting position.  This means that you don't have to distinguish\n\
  4378. between click and drag, double, or triple events unless you want to.\n\
  4379. \n\
  4380. `read-key-sequence' prefixes mouse events on mode lines, the vertical\n\
  4381. lines separating windows, and scroll bars with imaginary keys\n\
  4382. `mode-line', `vertical-line', and `vertical-scroll-bar'.\n\
  4383. \n\
  4384. If the user switches frames in the middle of a key sequence, the\n\
  4385. frame-switch event is put off until after the current key sequence.\n\
  4386. \n\
  4387. `read-key-sequence' checks `function-key-map' for function key\n\
  4388. sequences, where they wouldn't conflict with ordinary bindings.  See\n\
  4389. `function-key-map' for more details.")
  4390.   (prompt, continue_echo)
  4391.      Lisp_Object prompt, continue_echo;
  4392. {
  4393.   Lisp_Object keybuf[30];
  4394.   register int i;
  4395.   struct gcpro gcpro1;
  4396.  
  4397.   if (!NILP (prompt))
  4398.     CHECK_STRING (prompt, 0);
  4399.   QUIT;
  4400.  
  4401.   bzero (keybuf, sizeof keybuf);
  4402.   GCPRO1 (keybuf[0]);
  4403.   gcpro1.nvars = (sizeof keybuf/sizeof (keybuf[0]));
  4404.  
  4405.   if (NILP (continue_echo))
  4406.     this_command_key_count = 0;
  4407.  
  4408.   i = read_key_sequence (keybuf, (sizeof keybuf/sizeof (keybuf[0])),
  4409.              NILP (prompt) ? 0 : XSTRING (prompt)->data);
  4410.  
  4411.   if (i == -1)
  4412.     {
  4413.       Vquit_flag = Qt;
  4414.       QUIT;
  4415.     }
  4416.   UNGCPRO;
  4417.   return make_event_array (i, keybuf);
  4418. }
  4419.  
  4420. DEFUN ("command-execute", Fcommand_execute, Scommand_execute, 1, 2, 0,
  4421.  "Execute CMD as an editor command.\n\
  4422. CMD must be a symbol that satisfies the `commandp' predicate.\n\
  4423. Optional second arg RECORD-FLAG non-nil\n\
  4424. means unconditionally put this command in `command-history'.\n\
  4425. Otherwise, that is done only if an arg is read using the minibuffer.")
  4426.      (cmd, record)
  4427.      Lisp_Object cmd, record;
  4428. {
  4429.   register Lisp_Object final;
  4430.   register Lisp_Object tem;
  4431.   Lisp_Object prefixarg;
  4432.   struct backtrace backtrace;
  4433.   extern int debug_on_next_call;
  4434.  
  4435.   prefixarg = Vprefix_arg, Vprefix_arg = Qnil;
  4436.   Vcurrent_prefix_arg = prefixarg;
  4437.   debug_on_next_call = 0;
  4438.  
  4439.   if (XTYPE (cmd) == Lisp_Symbol)
  4440.     {
  4441.       tem = Fget (cmd, Qdisabled);
  4442.       if (!NILP (tem))
  4443.     return call1 (Vrun_hooks, Qdisabled_command_hook);
  4444.     }
  4445.  
  4446.   while (1)
  4447.     {
  4448.       final = Findirect_function (cmd);
  4449.  
  4450.       if (CONSP (final) && (tem = Fcar (final), EQ (tem, Qautoload)))
  4451.     do_autoload (final, cmd);
  4452.       else
  4453.     break;
  4454.     }
  4455.  
  4456.   if (XTYPE (final) == Lisp_String
  4457.       || XTYPE (final) == Lisp_Vector)
  4458.     {
  4459.       /* If requested, place the macro in the command history.  For
  4460.      other sorts of commands, call-interactively takes care of
  4461.      this.  */
  4462.       if (!NILP (record))
  4463.     Vcommand_history
  4464.       = Fcons (Fcons (Qexecute_kbd_macro,
  4465.               Fcons (final, Fcons (prefixarg, Qnil))),
  4466.            Vcommand_history);
  4467.  
  4468.       return Fexecute_kbd_macro (final, prefixarg);
  4469.     }
  4470.   if (CONSP (final) || XTYPE (final) == Lisp_Subr
  4471.       || XTYPE (final) == Lisp_Compiled)
  4472.     {
  4473.       backtrace.next = backtrace_list;
  4474.       backtrace_list = &backtrace;
  4475.       backtrace.function = &Qcall_interactively;
  4476.       backtrace.args = &cmd;
  4477.       backtrace.nargs = 1;
  4478.       backtrace.evalargs = 0;
  4479.  
  4480.       tem = Fcall_interactively (cmd, record);
  4481.  
  4482.       backtrace_list = backtrace.next;
  4483.       return tem;
  4484.     }
  4485.   return Qnil;
  4486. }
  4487.  
  4488. DEFUN ("execute-extended-command", Fexecute_extended_command, Sexecute_extended_command,
  4489.   1, 1, "P",
  4490.   "Read function name, then read its arguments and call it.")
  4491.   (prefixarg)
  4492.      Lisp_Object prefixarg;
  4493. {
  4494.   Lisp_Object function;
  4495.   char buf[40];
  4496.   Lisp_Object saved_keys;
  4497.   struct gcpro gcpro1;
  4498.  
  4499.   saved_keys = Fthis_command_keys ();
  4500.   buf[0] = 0;
  4501.   GCPRO1 (saved_keys);
  4502.  
  4503.   if (EQ (prefixarg, Qminus))
  4504.     strcpy (buf, "- ");
  4505.   else if (CONSP (prefixarg) && XINT (XCONS (prefixarg)->car) == 4)
  4506.     strcpy (buf, "C-u ");
  4507.   else if (CONSP (prefixarg) && XTYPE (XCONS (prefixarg)->car) == Lisp_Int)
  4508.     sprintf (buf, "%d ", XINT (XCONS (prefixarg)->car));
  4509.   else if (XTYPE (prefixarg) == Lisp_Int)
  4510.     sprintf (buf, "%d ", XINT (prefixarg));
  4511.  
  4512.   /* This isn't strictly correct if execute-extended-command
  4513.      is bound to anything else.  Perhaps it should use
  4514.      this_command_keys?  */
  4515.   strcat (buf, "M-x ");
  4516.  
  4517.   /* Prompt with buf, and then read a string, completing from and
  4518.      restricting to the set of all defined commands.  Don't provide
  4519.      any initial input.  The last Qnil says not to perform a 
  4520.      peculiar hack on the initial input.  */
  4521.   function = Fcompleting_read (build_string (buf),
  4522.                    Vobarray, Qcommandp,
  4523.                    Qt, Qnil, Qnil);
  4524.  
  4525.   /* Set this_command_keys to the concatenation of saved_keys and
  4526.      function, followed by a RET.  */
  4527.   {
  4528.     struct Lisp_String *str;
  4529.     int i;
  4530.     Lisp_Object tem;
  4531.  
  4532.     this_command_key_count = 0;
  4533.  
  4534.     str = XSTRING (saved_keys);
  4535.     for (i = 0; i < str->size; i++)
  4536.       {
  4537.     XFASTINT (tem) = str->data[i];
  4538.     add_command_key (tem);
  4539.       }
  4540.  
  4541.     str = XSTRING (function);
  4542.     for (i = 0; i < str->size; i++)
  4543.       {
  4544.     XFASTINT (tem) = str->data[i];
  4545.     add_command_key (tem);
  4546.       }
  4547.  
  4548.     XFASTINT (tem) = '\015';
  4549.     add_command_key (tem);
  4550.   }
  4551.  
  4552.   UNGCPRO;
  4553.  
  4554.   function = Fintern (function, Qnil);
  4555.   Vprefix_arg = prefixarg;
  4556.   this_command = function;
  4557.  
  4558.   return Fcommand_execute (function, Qt);
  4559. }
  4560.  
  4561.  
  4562. int
  4563. detect_input_pending ()
  4564. {
  4565.   if (!input_pending)
  4566.     get_input_pending (&input_pending);
  4567.  
  4568.   return input_pending;
  4569. }
  4570.  
  4571. /* This is called in some cases before a possible quit.
  4572.    It cases the next call to detect_input_pending to recompute input_pending.
  4573.    So calling this function unnecessarily can't do any harm.  */
  4574. _VOID_
  4575. clear_input_pending ()
  4576. {
  4577.   input_pending = 0;
  4578. }
  4579.  
  4580. DEFUN ("input-pending-p", Finput_pending_p, Sinput_pending_p, 0, 0, 0,
  4581.   "T if command input is currently available with no waiting.\n\
  4582. Actually, the value is nil only if we can be sure that no input is available.")
  4583.   ()
  4584. {
  4585.   if (!NILP (unread_command_events) || unread_command_char != -1)
  4586.     return (Qt);
  4587.  
  4588.   return detect_input_pending () ? Qt : Qnil;
  4589. }
  4590.  
  4591. DEFUN ("recent-keys", Frecent_keys, Srecent_keys, 0, 0, 0,
  4592.   "Return vector of last 100 events, not counting those from keyboard macros.")
  4593.   ()
  4594. {
  4595.   Lisp_Object *keys = XVECTOR (recent_keys)->contents;
  4596.   Lisp_Object val;
  4597.  
  4598.   if (total_keys < NUM_RECENT_KEYS)
  4599.     return Fvector (total_keys, keys);
  4600.   else
  4601.     {
  4602.       val = Fvector (NUM_RECENT_KEYS, keys);
  4603.       bcopy (keys + recent_keys_index,
  4604.          XVECTOR (val)->contents,
  4605.          (NUM_RECENT_KEYS - recent_keys_index) * sizeof (Lisp_Object));
  4606.       bcopy (keys,
  4607.          XVECTOR (val)->contents + NUM_RECENT_KEYS - recent_keys_index,
  4608.          recent_keys_index * sizeof (Lisp_Object));
  4609.       return val;
  4610.     }
  4611. }
  4612.  
  4613. DEFUN ("this-command-keys", Fthis_command_keys, Sthis_command_keys, 0, 0, 0,
  4614.   "Return the key sequence that invoked this command.\n\
  4615. The value is a string or a vector.")
  4616.   ()
  4617. {
  4618.   return make_event_array (this_command_key_count,
  4619.                XVECTOR (this_command_keys)->contents);
  4620. }
  4621.  
  4622. DEFUN ("recursion-depth", Frecursion_depth, Srecursion_depth, 0, 0, 0,
  4623.   "Return the current depth in recursive edits.")
  4624.   ()
  4625. {
  4626.   Lisp_Object temp;
  4627.   XFASTINT (temp) = command_loop_level + minibuf_level;
  4628.   return temp;
  4629. }
  4630.  
  4631. DEFUN ("open-dribble-file", Fopen_dribble_file, Sopen_dribble_file, 1, 1,
  4632.   "FOpen dribble file: ",
  4633.   "Start writing all keyboard characters to a dribble file called FILE.\n\
  4634. If FILE is nil, close any open dribble file.")
  4635.   (file)
  4636.      Lisp_Object file;
  4637. {
  4638.   if (NILP (file))
  4639.     {
  4640.       fclose (dribble);
  4641.       dribble = 0;
  4642.     }
  4643.   else
  4644.     {
  4645.       file = Fexpand_file_name (file, Qnil);
  4646. #ifdef WINDOWSNT
  4647.       dribble = fopen (XSTRING (file)->data, "wb");
  4648. #else /* !WINDOWSNT */
  4649.       dribble = fopen (XSTRING (file)->data, "w");
  4650. #endif /* !WINDOWSNT */
  4651.     }
  4652.   return Qnil;
  4653. }
  4654.  
  4655. DEFUN ("discard-input", Fdiscard_input, Sdiscard_input, 0, 0, 0,
  4656.   "Discard the contents of the terminal input buffer.\n\
  4657. Also cancel any kbd macro being defined.")
  4658.   ()
  4659. {
  4660.   defining_kbd_macro = 0;
  4661.   update_mode_lines++;
  4662.  
  4663.   unread_command_events = Qnil;
  4664.   unread_command_char = -1;
  4665.  
  4666.   discard_tty_input ();
  4667.  
  4668.   /* Without the cast, GCC complains that this assignment loses the
  4669.      volatile qualifier of kbd_store_ptr.  Is there anything wrong
  4670.      with that?  */
  4671.   kbd_fetch_ptr = (struct input_event *) kbd_store_ptr;
  4672.   Ffillarray (kbd_buffer_frame_or_window, Qnil);
  4673.   input_pending = 0;
  4674.  
  4675.   return Qnil;
  4676. }
  4677.  
  4678. DEFUN ("suspend-emacs", Fsuspend_emacs, Ssuspend_emacs, 0, 1, "",
  4679.   "Stop Emacs and return to superior process.  You can resume later.\n\
  4680. On systems that don't have job control, run a subshell instead.\n\n\
  4681. If optional arg STUFFSTRING is non-nil, its characters are stuffed\n\
  4682. to be read as terminal input by Emacs's parent, after suspension.\n\
  4683. \n\
  4684. Before suspending, call the functions in `suspend-hook' with no args.\n\
  4685. If any of them returns nil, don't call the rest and don't suspend.\n\
  4686. Otherwise, suspend normally and after resumption run the normal hook\n\
  4687. `suspend-resume-hook' if that is bound and non-nil.\n\
  4688. \n\
  4689. Some operating systems cannot stop the Emacs process and resume it later.\n\
  4690. On such systems, Emacs starts a subshell instead of suspending.")
  4691.   (stuffstring)
  4692.      Lisp_Object stuffstring;
  4693. {
  4694.   int count = specpdl_ptr - specpdl;
  4695.   int old_height, old_width;
  4696.   int width, height;
  4697.   struct gcpro gcpro1;
  4698. #ifndef USE_PROTOTYPES
  4699.   extern init_sys_modes ();
  4700. #endif
  4701.  
  4702.   if (!NILP (stuffstring))
  4703.     CHECK_STRING (stuffstring, 0);
  4704.  
  4705.   /* Run the functions in suspend-hook.  */
  4706.   if (!NILP (Vrun_hooks))
  4707.     call1 (Vrun_hooks, intern ("suspend-hook"));
  4708.  
  4709.   GCPRO1 (stuffstring);
  4710.   get_frame_size (&old_width, &old_height);
  4711.   reset_sys_modes ();
  4712.   /* sys_suspend can get an error if it tries to fork a subshell
  4713.      and the system resources aren't available for that.  */
  4714.   record_unwind_protect (init_sys_modes, 0);
  4715.   stuff_buffered_input (stuffstring);
  4716.   sys_suspend ();
  4717.   unbind_to (count, Qnil);
  4718.  
  4719.   /* Check if terminal/window size has changed.
  4720.      Note that this is not useful when we are running directly
  4721.      with a window system; but suspend should be disabled in that case.  */
  4722.   get_frame_size (&width, &height);
  4723.   if (width != old_width || height != old_height)
  4724.     change_frame_size (selected_frame, height, width, 0, 0);
  4725.  
  4726.   /* Run suspend-resume-hook.  */
  4727.   if (!NILP (Vrun_hooks))
  4728.     call1 (Vrun_hooks, intern ("suspend-resume-hook"));
  4729.   
  4730.   UNGCPRO;
  4731.   return Qnil;
  4732. }
  4733.  
  4734. /* If STUFFSTRING is a string, stuff its contents as pending terminal input.
  4735.    Then in any case stuff anything Emacs has read ahead and not used.  */
  4736.  
  4737. _VOID_
  4738. stuff_buffered_input (stuffstring)
  4739.      Lisp_Object stuffstring;
  4740. {
  4741. /* stuff_char works only in BSD, versions 4.2 and up.  */
  4742. #ifdef BSD
  4743. #ifndef BSD4_1
  4744.   register unsigned char *p;
  4745.  
  4746.   if (XTYPE (stuffstring) == Lisp_String)
  4747.     {
  4748.       register int count;
  4749.  
  4750.       p = XSTRING (stuffstring)->data;
  4751.       count = XSTRING (stuffstring)->size;
  4752.       while (count-- > 0)
  4753.     stuff_char (*p++);
  4754.       stuff_char ('\n');
  4755.     }
  4756.   /* Anything we have read ahead, put back for the shell to read.  */
  4757.   while (kbd_fetch_ptr != kbd_store_ptr)
  4758.     {
  4759.       if (kbd_fetch_ptr == kbd_buffer + KBD_BUFFER_SIZE)
  4760.     kbd_fetch_ptr = kbd_buffer;
  4761.       if (kbd_fetch_ptr->kind == ascii_keystroke)
  4762.     stuff_char (XINT (kbd_fetch_ptr->code));
  4763.       kbd_fetch_ptr->kind = no_event;
  4764.       (XVECTOR (kbd_buffer_frame_or_window)->contents[kbd_fetch_ptr
  4765.                              - kbd_buffer]
  4766.        = Qnil);
  4767.       kbd_fetch_ptr++;
  4768.     }
  4769.   input_pending = 0;
  4770. #endif
  4771. #endif /* BSD and not BSD4_1 */
  4772. }
  4773.  
  4774. _VOID_
  4775. set_waiting_for_input (time_to_clear)
  4776.      EMACS_TIME *time_to_clear;
  4777. {
  4778.   input_available_clear_time = time_to_clear;
  4779.  
  4780.   /* Tell interrupt_signal to throw back to read_char,  */
  4781.   waiting_for_input = 1;
  4782.  
  4783.   /* If interrupt_signal was called before and buffered a C-g,
  4784.      make it run again now, to avoid timing error. */
  4785.   if (!NILP (Vquit_flag))
  4786.     quit_throw_to_read_char ();
  4787.  
  4788.   /* If alarm has gone off already, echo now.  */
  4789.   if (echo_flag)
  4790.     {
  4791.       echo ();
  4792.       echo_flag = 0;
  4793.     }
  4794. }
  4795.  
  4796. _VOID_
  4797. clear_waiting_for_input ()
  4798. {
  4799.   /* Tell interrupt_signal not to throw back to read_char,  */
  4800.   waiting_for_input = 0;
  4801.   input_available_clear_time = 0;
  4802. }
  4803.  
  4804. /* This routine is called at interrupt level in response to C-G.
  4805.  If interrupt_input, this is the handler for SIGINT.
  4806.  Otherwise, it is called from kbd_buffer_store_event,
  4807.  in handling SIGIO or SIGTINT.
  4808.  
  4809.  If `waiting_for_input' is non zero, then unless `echoing' is nonzero,
  4810.  immediately throw back to read_char.
  4811.  
  4812.  Otherwise it sets the Lisp variable  quit-flag  not-nil.
  4813.  This causes  eval  to throw, when it gets a chance.
  4814.  If  quit-flag  is already non-nil, it stops the job right away.  */
  4815.  
  4816. SIGTYPE
  4817. interrupt_signal ()
  4818. {
  4819.   char c;
  4820.   /* Must preserve main program's value of errno.  */
  4821.   int old_errno = errno;
  4822.  
  4823. #ifdef USG
  4824.   /* USG systems forget handlers when they are used;
  4825.      must reestablish each time */
  4826.   signal (SIGINT, interrupt_signal);
  4827.   signal (SIGQUIT, interrupt_signal);
  4828. #endif /* USG */
  4829.  
  4830.   cancel_echoing ();
  4831.  
  4832.   if (!NILP (Vquit_flag) && FRAME_TERMCAP_P (selected_frame))
  4833.     {
  4834.       fflush (stdout);
  4835.       reset_sys_modes ();
  4836. #ifndef WINDOWSNT
  4837.       sigfree ();
  4838. #endif
  4839. #ifdef SIGTSTP            /* Support possible in later USG versions */
  4840. /*
  4841.  * On systems which can suspend the current process and return to the original
  4842.  * shell, this command causes the user to end up back at the shell.
  4843.  * The "Auto-save" and "Abort" questions are not asked until
  4844.  * the user elects to return to emacs, at which point he can save the current
  4845.  * job and either dump core or continue.
  4846.  */
  4847.       sys_suspend ();
  4848. #else
  4849. #ifdef VMS
  4850.       if (sys_suspend () == -1)
  4851.     {
  4852.       printf ("Not running as a subprocess;\n");
  4853.       printf ("you can continue or abort.\n");
  4854.     }
  4855. #else /* not VMS */
  4856.       /* Perhaps should really fork an inferior shell?
  4857.      But that would not provide any way to get back
  4858.      to the original shell, ever.  */
  4859.       printf ("No support for stopping a process on this operating system;\n");
  4860.       printf ("you can continue or abort.\n");
  4861. #endif /* not VMS */
  4862. #endif /* not SIGTSTP */
  4863.       printf ("Auto-save? (y or n) ");
  4864.       fflush (stdout);
  4865.       if (((c = getchar ()) & ~040) == 'Y')
  4866.     Fdo_auto_save (Qnil, Qnil);
  4867.       while (c != '\n') c = getchar ();
  4868. #ifdef VMS
  4869.       printf ("Abort (and enter debugger)? (y or n) ");
  4870. #else /* not VMS */
  4871.       printf ("Abort (and dump core)? (y or n) ");
  4872. #endif /* not VMS */
  4873.       fflush (stdout);
  4874.       if (((c = getchar ()) & ~040) == 'Y')
  4875.     abort ();
  4876.       while (c != '\n') c = getchar ();
  4877.       printf ("Continuing...\n");
  4878.       fflush (stdout);
  4879.       init_sys_modes (Qt);
  4880.     }
  4881.   else
  4882.     {
  4883.       /* If executing a function that wants to be interrupted out of
  4884.      and the user has not deferred quitting by binding `inhibit-quit'
  4885.      then quit right away.  */
  4886.       if (immediate_quit && NILP (Vinhibit_quit))
  4887.     {
  4888.       immediate_quit = 0;
  4889. #ifndef WINDOWSNT
  4890.           sigfree ();
  4891. #endif
  4892.       Fsignal (Qquit, Qnil);
  4893.     }
  4894.       else
  4895.     /* Else request quit when it's safe */
  4896.     Vquit_flag = Qt;
  4897.     }
  4898.  
  4899.   if (waiting_for_input && !echoing)
  4900.     quit_throw_to_read_char ();
  4901.  
  4902.   errno = old_errno;
  4903. }
  4904.  
  4905. /* Handle a C-g by making read_char return C-g.  */
  4906.  
  4907. _VOID_
  4908. quit_throw_to_read_char ()
  4909. {
  4910.   quit_error_check ();
  4911. #ifndef WINDOWSNT
  4912.   sigfree ();
  4913. #endif
  4914.   /* Prevent another signal from doing this before we finish.  */
  4915.   clear_waiting_for_input ();
  4916.   input_pending = 0;
  4917.  
  4918.   unread_command_events = Qnil;
  4919.   unread_command_char = -1;
  4920.  
  4921. #ifdef POLL_FOR_INPUT
  4922.   /* May be > 1 if in recursive minibuffer.  */
  4923.   if (poll_suppress_count == 0)
  4924.     abort ();
  4925. #endif
  4926.  
  4927.   _longjmp (getcjmp, 1);
  4928. }
  4929.  
  4930. DEFUN ("set-input-mode", Fset_input_mode, Sset_input_mode, 3, 4, 0,
  4931.   "Set mode of reading keyboard input.\n\
  4932. First arg INTERRUPT non-nil means use input interrupts;\n\
  4933.  nil means use CBREAK mode.\n\
  4934. Second arg FLOW non-nil means use ^S/^Q flow control for output to terminal\n\
  4935.  (no effect except in CBREAK mode).\n\
  4936. Third arg META t means accept 8-bit input (for a Meta key).\n\
  4937.  META nil means ignore the top bit, on the assumption it is parity.\n\
  4938.  Otherwise, accept 8-bit input and don't use the top bit for Meta.\n\
  4939. Optional fourth arg QUIT if non-nil specifies character to use for quitting.\n\
  4940. See also `current-input-mode'.")
  4941.   (interrupt, flow, meta, quit)
  4942.      Lisp_Object interrupt, flow, meta, quit;
  4943. {
  4944.   if (!NILP (quit)
  4945.       && (XTYPE (quit) != Lisp_Int
  4946.       || XINT (quit) < 0 || XINT (quit) > 0400))
  4947.     error ("set-input-mode: QUIT must be an ASCII character.");
  4948.  
  4949.   reset_sys_modes ();
  4950. #ifdef SIGIO
  4951. /* Note SIGIO has been undef'd if FIONREAD is missing.  */
  4952. #ifdef NO_SOCK_SIGIO
  4953.   if (read_socket_hook)
  4954.     interrupt_input = 0;    /* No interrupts if reading from a socket.  */
  4955.   else
  4956. #endif /* NO_SOCK_SIGIO */
  4957.     interrupt_input = !NILP (interrupt);
  4958. #else /* not SIGIO */
  4959.   interrupt_input = 0;
  4960. #endif /* not SIGIO */
  4961. /* Our VMS input only works by interrupts, as of now.  */
  4962. #ifdef VMS
  4963.   interrupt_input = 1;
  4964. #endif
  4965.   flow_control = !NILP (flow);
  4966.   if (NILP (meta))
  4967.     meta_key = 0;
  4968.   else if (EQ (meta, Qt))
  4969.     meta_key = 1;
  4970.   else
  4971.     meta_key = 2;
  4972.   if (!NILP (quit))
  4973.     /* Don't let this value be out of range.  */
  4974.     quit_char = XINT (quit) & (meta_key ? 0377 : 0177);
  4975.  
  4976.   init_sys_modes (Qt);
  4977.   return Qnil;
  4978. }
  4979.  
  4980. DEFUN ("current-input-mode", Fcurrent_input_mode, Scurrent_input_mode, 0, 0, 0,
  4981.   "Return information about the way Emacs currently reads keyboard input.\n\
  4982. The value is a list of the form (INTERRUPT FLOW META QUIT), where\n\
  4983.   INTERRUPT is non-nil if Emacs is using interrupt-driven input; if\n\
  4984.     nil, Emacs is using CBREAK mode.\n\
  4985.   FLOW is non-nil if Emacs uses ^S/^Q flow control for output to the\n\
  4986.     terminal; this does not apply if Emacs uses interrupt-driven input.\n\
  4987.   META is t if accepting 8-bit input with 8th bit as Meta flag.\n\
  4988.     META nil means ignoring the top bit, on the assumption it is parity.\n\
  4989.     META is neither t nor nil if accepting 8-bit input and using\n\
  4990.     all 8 bits as the character code.\n\
  4991.   QUIT is the character Emacs currently uses to quit.\n\
  4992. The elements of this list correspond to the arguments of\n\
  4993. `set-input-mode'.")
  4994.   ()
  4995. {
  4996.   Lisp_Object val[4];
  4997.  
  4998.   val[0] = interrupt_input ? Qt : Qnil;
  4999.   val[1] = flow_control ? Qt : Qnil;
  5000.   val[2] = meta_key == 2 ? make_number (0) : meta_key == 1 ? Qt : Qnil;
  5001.   XFASTINT (val[3]) = quit_char;
  5002.  
  5003.   return Flist (sizeof (val) / sizeof (val[0]), val);
  5004. }
  5005.  
  5006.  
  5007. _VOID_
  5008. init_keyboard ()
  5009. {
  5010.   /* This is correct before outermost invocation of the editor loop */
  5011.   command_loop_level = -1;
  5012.   immediate_quit = 0;
  5013.   quit_char = Ctl ('g');
  5014.   unread_command_events = Qnil;
  5015.   unread_command_char = -1;
  5016.   total_keys = 0;
  5017.   recent_keys_index = 0;
  5018.   kbd_fetch_ptr = kbd_buffer;
  5019.   kbd_store_ptr = kbd_buffer;
  5020.   do_mouse_tracking = 0;
  5021.   input_pending = 0;
  5022.  
  5023. #ifdef MULTI_FRAME
  5024.   /* This means that command_loop_1 won't try to select anything the first
  5025.      time through.  */
  5026.   internal_last_event_frame = Qnil;
  5027.   Vlast_event_frame = internal_last_event_frame;
  5028. #endif
  5029.  
  5030.   /* If we're running a dumped Emacs, we need to clear out
  5031.      kbd_buffer_frame_or_window, in case some events got into it
  5032.      before we dumped.
  5033.  
  5034.      If we're running an undumped Emacs, it hasn't been initialized by
  5035.      syms_of_keyboard yet.  */
  5036.   if (initialized)
  5037.     Ffillarray (kbd_buffer_frame_or_window, Qnil);
  5038.  
  5039. #ifndef WINDOWSNT
  5040.   if (!noninteractive)
  5041.     {
  5042.       signal (SIGINT, interrupt_signal);
  5043. #if defined (HAVE_TERMIO) || defined (HAVE_TERMIOS)
  5044.       /* For systems with SysV TERMIO, C-g is set up for both SIGINT and
  5045.      SIGQUIT and we can't tell which one it will give us.  */
  5046.       signal (SIGQUIT, interrupt_signal);
  5047. #endif /* HAVE_TERMIO */
  5048. /* Note SIGIO has been undef'd if FIONREAD is missing.  */
  5049. #ifdef SIGIO
  5050.       signal (SIGIO, input_available_signal);
  5051. #endif /* SIGIO */
  5052.     }
  5053. #endif /* !WINDOWSNT */
  5054.  
  5055. /* Use interrupt input by default, if it works and noninterrupt input
  5056.    has deficiencies.  */
  5057.  
  5058. #ifdef INTERRUPT_INPUT
  5059.   interrupt_input = 1;
  5060. #else
  5061.   interrupt_input = 0;
  5062. #endif
  5063.  
  5064. /* Our VMS input only works by interrupts, as of now.  */
  5065. #ifdef VMS
  5066.   interrupt_input = 1;
  5067. #endif
  5068.  
  5069. #ifndef WINDOWSNT
  5070.   sigfree ();
  5071. #endif /* !WINDOWSNT */
  5072.   dribble = 0;
  5073.  
  5074.   if (keyboard_init_hook)
  5075.     (*keyboard_init_hook) ();
  5076.  
  5077. #ifdef POLL_FOR_INPUT
  5078.   poll_suppress_count = 1;
  5079.   start_polling ();
  5080. #endif
  5081. }
  5082.  
  5083. /* This type's only use is in syms_of_keyboard, to initialize the 
  5084.    event header symbols and put properties on them.  */
  5085. struct event_head {
  5086.   Lisp_Object *var;
  5087.   char *name;
  5088.   Lisp_Object *kind;
  5089. };
  5090.  
  5091. struct event_head head_table[] = {
  5092.   &Qmouse_movement,    "mouse-movement",    &Qmouse_movement,
  5093.   &Qscroll_bar_movement, "scroll-bar-movement",    &Qmouse_movement,
  5094.   &Qswitch_frame,    "switch-frame",        &Qswitch_frame,
  5095. };
  5096.  
  5097. _VOID_
  5098. syms_of_keyboard ()
  5099. {
  5100.   Qdisabled_command_hook = intern ("disabled-command-hook");
  5101.   staticpro (&Qdisabled_command_hook);
  5102.  
  5103.   Qself_insert_command = intern ("self-insert-command");
  5104.   staticpro (&Qself_insert_command);
  5105.  
  5106.   Qforward_char = intern ("forward-char");
  5107.   staticpro (&Qforward_char);
  5108.  
  5109.   Qbackward_char = intern ("backward-char");
  5110.   staticpro (&Qbackward_char);
  5111.  
  5112.   Qdisabled = intern ("disabled");
  5113.   staticpro (&Qdisabled);
  5114.  
  5115.   Qundefined = intern ("undefined");
  5116.   staticpro (&Qundefined);
  5117.  
  5118.   Qpre_command_hook = intern ("pre-command-hook");
  5119.   staticpro (&Qpre_command_hook);
  5120.  
  5121.   Qpost_command_hook = intern ("post-command-hook");
  5122.   staticpro (&Qpost_command_hook);
  5123.  
  5124.   Qfunction_key = intern ("function-key");
  5125.   staticpro (&Qfunction_key);
  5126.   Qmouse_click = intern ("mouse-click");
  5127.   staticpro (&Qmouse_click);
  5128.  
  5129.   Qmenu_enable = intern ("menu-enable");
  5130.   staticpro (&Qmenu_enable);
  5131.  
  5132.   Qmode_line = intern ("mode-line");
  5133.   staticpro (&Qmode_line);
  5134.   Qvertical_line = intern ("vertical-line");
  5135.   staticpro (&Qvertical_line);
  5136.   Qvertical_scroll_bar = intern ("vertical-scroll-bar");
  5137.   staticpro (&Qvertical_scroll_bar);
  5138.   Qmenu_bar = intern ("menu-bar");
  5139.   staticpro (&Qmenu_bar);
  5140.  
  5141.   Qabove_handle = intern ("above-handle");
  5142.   staticpro (&Qabove_handle);
  5143.   Qhandle = intern ("handle");
  5144.   staticpro (&Qhandle);
  5145.   Qbelow_handle = intern ("below-handle");
  5146.   staticpro (&Qbelow_handle);
  5147.  
  5148.   Qevent_kind = intern ("event-kind");
  5149.   staticpro (&Qevent_kind);
  5150.   Qevent_symbol_elements = intern ("event-symbol-elements");
  5151.   staticpro (&Qevent_symbol_elements);
  5152.   Qevent_symbol_element_mask = intern ("event-symbol-element-mask");
  5153.   staticpro (&Qevent_symbol_element_mask);
  5154.   Qmodifier_cache = intern ("modifier-cache");
  5155.   staticpro (&Qmodifier_cache);
  5156.  
  5157.   Qrecompute_lucid_menubar = intern ("recompute-lucid-menubar");
  5158.   staticpro (&Qrecompute_lucid_menubar);
  5159.   Qactivate_menubar_hook = intern ("activate-menubar-hook");
  5160.   staticpro (&Qactivate_menubar_hook);
  5161.  
  5162.   {
  5163.     struct event_head *p;
  5164.  
  5165.     for (p = head_table;
  5166.      p < head_table + (sizeof (head_table) / sizeof (head_table[0]));
  5167.      p++)
  5168.       {
  5169.     *p->var = intern (p->name);
  5170.     staticpro (p->var);
  5171.     Fput (*p->var, Qevent_kind, *p->kind);
  5172.     Fput (*p->var, Qevent_symbol_elements, Fcons (*p->var, Qnil));
  5173.       }
  5174.   }
  5175.  
  5176.   button_down_location = Fmake_vector (make_number (NUM_MOUSE_BUTTONS), Qnil);
  5177.   staticpro (&button_down_location);
  5178.  
  5179.   {
  5180.     int i;
  5181.     int len = sizeof (modifier_names) / sizeof (modifier_names[0]);
  5182.  
  5183.     modifier_symbols = Fmake_vector (make_number (len), Qnil);
  5184.     for (i = 0; i < len; i++)
  5185.       if (modifier_names[i])
  5186.     XVECTOR (modifier_symbols)->contents[i] = intern (modifier_names[i]);
  5187.     staticpro (&modifier_symbols);
  5188.   }
  5189.  
  5190.   recent_keys = Fmake_vector (make_number (NUM_RECENT_KEYS), Qnil);
  5191.   staticpro (&recent_keys);
  5192.  
  5193.   this_command_keys = Fmake_vector (make_number (40), Qnil);
  5194.   staticpro (&this_command_keys);
  5195.  
  5196.   kbd_buffer_frame_or_window
  5197.     = Fmake_vector (make_number (KBD_BUFFER_SIZE), Qnil);
  5198.   staticpro (&kbd_buffer_frame_or_window);
  5199.  
  5200.   func_key_syms = Qnil;
  5201.   staticpro (&func_key_syms);
  5202.  
  5203.   mouse_syms = Qnil;
  5204.   staticpro (&mouse_syms);
  5205.  
  5206.   unread_switch_frame = Qnil;
  5207.   staticpro (&unread_switch_frame);
  5208.  
  5209.   defsubr (&Sread_key_sequence);
  5210.   defsubr (&Srecursive_edit);
  5211.   defsubr (&Strack_mouse);
  5212.   defsubr (&Sinput_pending_p);
  5213.   defsubr (&Scommand_execute);
  5214.   defsubr (&Srecent_keys);
  5215.   defsubr (&Sthis_command_keys);
  5216.   defsubr (&Ssuspend_emacs);
  5217.   defsubr (&Sabort_recursive_edit);
  5218.   defsubr (&Sexit_recursive_edit);
  5219.   defsubr (&Srecursion_depth);
  5220.   defsubr (&Stop_level);
  5221.   defsubr (&Sdiscard_input);
  5222.   defsubr (&Sopen_dribble_file);
  5223.   defsubr (&Sset_input_mode);
  5224.   defsubr (&Scurrent_input_mode);
  5225.   defsubr (&Sexecute_extended_command);
  5226.  
  5227.   DEFVAR_LISP ("last-command-char", &last_command_char,
  5228.     "Last input event that was part of a command.");
  5229.  
  5230.   DEFVAR_LISP ("last-command-event", &last_command_char,
  5231.     "Last input event that was part of a command.");
  5232.  
  5233.   DEFVAR_LISP ("last-nonmenu-event", &last_nonmenu_event,
  5234.     "Last input event in a command, except for mouse menu events.\n\
  5235. Mouse menus give back keys that don't look like mouse events;\n\
  5236. this variable holds the actual mouse event that led to the menu,\n\
  5237. so that you can determine whether the command was run by mouse or not.");
  5238.  
  5239.   DEFVAR_LISP ("last-input-char", &last_input_char,
  5240.     "Last input event.");
  5241.  
  5242.   DEFVAR_LISP ("last-input-event", &last_input_char,
  5243.     "Last input event.");
  5244.  
  5245.   DEFVAR_LISP ("unread-command-events", &unread_command_events,
  5246.     "List of objects to be read as next command input events.");
  5247.  
  5248.   DEFVAR_INT ("unread-command-char", &unread_command_char,
  5249.     "If not -1, an object to be read as next command input event.");
  5250.  
  5251.   DEFVAR_LISP ("meta-prefix-char", &meta_prefix_char,
  5252.     "Meta-prefix character code.  Meta-foo as command input\n\
  5253. turns into this character followed by foo.");
  5254.   XSET (meta_prefix_char, Lisp_Int, 033);
  5255.  
  5256.   DEFVAR_LISP ("last-command", &last_command,
  5257.     "The last command executed.  Normally a symbol with a function definition,\n\
  5258. but can be whatever was found in the keymap, or whatever the variable\n\
  5259. `this-command' was set to by that command.");
  5260.   last_command = Qnil;
  5261.  
  5262.   DEFVAR_LISP ("this-command", &this_command,
  5263.     "The command now being executed.\n\
  5264. The command can set this variable; whatever is put here\n\
  5265. will be in `last-command' during the following command.");
  5266.   this_command = Qnil;
  5267.  
  5268.   DEFVAR_INT ("auto-save-interval", &auto_save_interval,
  5269.     "*Number of keyboard input characters between auto-saves.\n\
  5270. Zero means disable autosaving due to number of characters typed.");
  5271.   auto_save_interval = 300;
  5272.  
  5273.   DEFVAR_LISP ("auto-save-timeout", &Vauto_save_timeout,
  5274.     "*Number of seconds idle time before auto-save.\n\
  5275. Zero or nil means disable auto-saving due to idleness.\n\
  5276. After auto-saving due to this many seconds of idle time,\n\
  5277. Emacs also does a garbage collection if that seems to be warranted.");
  5278.   XFASTINT (Vauto_save_timeout) = 30;
  5279.  
  5280.   DEFVAR_INT ("echo-keystrokes", &echo_keystrokes,
  5281.     "*Nonzero means echo unfinished commands after this many seconds of pause.");
  5282.   echo_keystrokes = 1;
  5283.  
  5284.   DEFVAR_INT ("polling-period", &polling_period,
  5285.     "*Interval between polling for input during Lisp execution.\n\
  5286. The reason for polling is to make C-g work to stop a running program.\n\
  5287. Polling is needed only when using X windows and SIGIO does not work.\n\
  5288. Polling is automatically disabled in all other cases.");
  5289.   polling_period = 2;
  5290.   
  5291.   DEFVAR_LISP ("double-click-time", &Vdouble_click_time,
  5292.     "*Maximum time between mouse clicks to make a double-click.\n\
  5293. Measured in milliseconds.  nil means disable double-click recognition;\n\
  5294. t means double-clicks have no time limit and are detected\n\
  5295. by position only.");
  5296.   Vdouble_click_time = make_number (500);
  5297.  
  5298.   DEFVAR_INT ("num-input-keys", &num_input_keys,
  5299.     "*Number of complete keys read from the keyboard so far.");
  5300.   num_input_keys = 0;
  5301.  
  5302. #ifdef MULTI_FRAME
  5303.   DEFVAR_LISP ("last-event-frame", &Vlast_event_frame,
  5304.     "*The frame in which the most recently read event occurred.\n\
  5305. If the last event came from a keyboard macro, this is set to `macro'.");
  5306.   Vlast_event_frame = Qnil;
  5307. #endif
  5308.  
  5309.   DEFVAR_LISP ("help-char", &Vhelp_char,
  5310.     "Character to recognize as meaning Help.\n\
  5311. When it is read, do `(eval help-form)', and display result if it's a string.\n\
  5312. If the value of `help-form' is nil, this char can be read normally.");
  5313.   XSET (Vhelp_char, Lisp_Int, Ctl ('H'));
  5314.  
  5315.   DEFVAR_LISP ("help-form", &Vhelp_form,
  5316.     "Form to execute when character `help-char' is read.\n\
  5317. If the form returns a string, that string is displayed.\n\
  5318. If `help-form' is nil, the help char is not recognized.");
  5319.   Vhelp_form = Qnil;
  5320.  
  5321.   DEFVAR_LISP ("prefix-help-command", &Vprefix_help_command,
  5322.     "Command to run when `help-char' character follows a prefix key.\n\
  5323. This command is used only when there is no actual binding\n\
  5324. for that character after that prefix key.");
  5325.   Vprefix_help_command = Qnil;
  5326.  
  5327.   DEFVAR_LISP ("top-level", &Vtop_level,
  5328.     "Form to evaluate when Emacs starts up.\n\
  5329. Useful to set before you dump a modified Emacs.");
  5330.   Vtop_level = Qnil;
  5331.  
  5332.   DEFVAR_LISP ("keyboard-translate-table", &Vkeyboard_translate_table,
  5333.     "String used as translate table for keyboard input, or nil.\n\
  5334. Each character is looked up in this string and the contents used instead.\n\
  5335. If string is of length N, character codes N and up are untranslated.");
  5336.   Vkeyboard_translate_table = Qnil;
  5337.  
  5338.   DEFVAR_BOOL ("menu-prompting", &menu_prompting,
  5339.     "Non-nil means prompt with menus when appropriate.\n\
  5340. This is done when reading from a keymap that has a prompt string,\n\
  5341. for elements that have prompt strings.\n\
  5342. The menu is displayed on the screen\n\
  5343. if X menus were enabled at configuration\n\
  5344. time and the previous event was a mouse click prefix key.\n\
  5345. Otherwise, menu prompting uses the echo area.");
  5346.   menu_prompting = 1;
  5347.  
  5348.   DEFVAR_LISP ("menu-prompt-more-char", &menu_prompt_more_char,
  5349.     "Character to see next line of menu prompt.\n\
  5350. Type this character while in a menu prompt to rotate around the lines of it.");
  5351.   XSET (menu_prompt_more_char, Lisp_Int, ' ');
  5352.  
  5353.   DEFVAR_INT ("extra-keyboard-modifiers", &extra_keyboard_modifiers,
  5354.     "A mask of additional modifier keys to use with every keyboard character.\n\
  5355. Emacs applies the modifiers of the character stored here to each keyboard\n\
  5356. character it reads.  For example, after evaluating the expression\n\
  5357.     (setq extra-keyboard-modifiers ?\C-x)\n\
  5358. all input characters will have the control modifier applied to them.\n\
  5359. \n\
  5360. Note that the character ?\C-@, equivalent to the integer zero, does\n\
  5361. not count as a control character; rather, it counts as a character\n\
  5362. with no modifiers; thus, setting extra_keyboard_modifiers to zero\n\
  5363. cancels any modification.");
  5364.   extra_keyboard_modifiers = 0;
  5365.  
  5366.   DEFVAR_LISP ("deactivate-mark", &Vdeactivate_mark,
  5367.     "If an editing command sets this to t, deactivate the mark afterward.\n\
  5368. The command loop sets this to nil before each command,\n\
  5369. and tests the value when the command returns.\n\
  5370. Buffer modification stores t in this variable.");
  5371.   Vdeactivate_mark = Qnil;
  5372.  
  5373.   DEFVAR_LISP ("pre-command-hook", &Vpre_command_hook,
  5374.     "Normal hook run before each command is executed.");
  5375.   Vpre_command_hook = Qnil;
  5376.  
  5377.   DEFVAR_LISP ("post-command-hook", &Vpost_command_hook,
  5378.     "Normal hook run after each command is executed.");
  5379.   Vpost_command_hook = Qnil;
  5380.  
  5381.   DEFVAR_LISP ("lucid-menu-bar-dirty-flag", &Vlucid_menu_bar_dirty_flag,
  5382.     "t means menu bar, specified Lucid style, needs to be recomputed.");
  5383.   Vlucid_menu_bar_dirty_flag = Qnil;
  5384.  
  5385.   DEFVAR_LISP ("menu-bar-final-items", &Vmenu_bar_final_items,
  5386.     "List of menu bar items to move to the end of the menu bar.\n\
  5387. The elements of the listare event types that may have menu bar bindings.");
  5388.   Vmenu_bar_final_items = Qnil;
  5389. }
  5390.  
  5391. _VOID_
  5392. keys_of_keyboard ()
  5393. {
  5394.   initial_define_key (global_map, Ctl ('Z'), "suspend-emacs");
  5395.   initial_define_key (control_x_map, Ctl ('Z'), "suspend-emacs");
  5396.   initial_define_key (meta_map, Ctl ('C'), "exit-recursive-edit");
  5397.   initial_define_key (global_map, Ctl (']'), "abort-recursive-edit");
  5398.   initial_define_key (meta_map, 'x', "execute-extended-command");
  5399. }
  5400.